When should I call ensureIndex? Before inserting a single record, after inserting a single record, or before calling find()?
When should I call ensureIndex ? Before inserting a single record, after inserting a
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
ensureIndexat the same time (and in the same place) as thefind()call.ensureIndexwill 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
ensureIndexin 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.)