Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb: when to call ensureIndex?

When should I call ensureIndex? Before inserting a single record, after inserting a single record, or before calling find()?

like image 651
Johnny Avatar asked Aug 09 '11 18:08

Johnny


2 Answers

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.)

like image 50
Code Magician Avatar answered Sep 28 '22 07:09

Code Magician


I'd recommend calling ensureIndex once, when your application starts.

like image 41
UpTheCreek Avatar answered Sep 28 '22 07:09

UpTheCreek