When should I call ensureIndex? Before inserting a single record, after inserting a single record, or before calling find()?
Regards,
Johnny
I typically put my ensureIndex()
calls within an init block for the part of my application that manages communication with MongoDB. Also, I wrap those ensureIndex()
calls within a check for existence of a collection I know must exist for the application to function; this way, the ensureIndex() calls are only ever called once, ever, the first time the application is run against a specific MongoDB instance.
I've read elsewhere an opinion against putting ensureIndex() calls in application code, as other developers can mistakenly change them and alter the DB (the indexes), but wrapping it in a check for a collection's existence helps to guard against this.
Java MongoDB driver example:
DB db = mongo.getDB("databaseName");
Set existingCollectionNames = db.getCollectionNames();
// init collections; ensureIndexes only if creating collection
// (let application set up the db if it's not already)
DBCollection coll = db.getCollection("collectionName");
if (!existingCollectionNames.contains("collectionName")) {
// ensure indexes...
coll.ensureIndex(BasicDBObjectBuilder.start().add("date", 1).get());
// ...
}