When to call ensureIndex on a MongoDB collection?

It seems my comment has been a little misunderstood, so I’ll clarify. It doesn’t really matter when you call it so long as it’s called at some point before you call find() for the first time. In other words, it doesn’t really matter when you create the index, as long as it’s there before you expect to use it.

A common pattern that I’ve seen a lot is coding the ensureIndex at the same time (and in the same place) as the find() call. ensureIndex will check if the index exists and create it if it doesn’t. There is undoubted some overhead (albeit very small) in calling ensureindex before ever call to find() so it’s preferable not to do this.

I do call ensureIndex in code to simplify deployments and to avoid having to manage the db and codebase separately. The tradeoff of ease of deployment balances out the redundancy of subsequent calls to ensureIndex (for me.)

Leave a Comment