Mongodb: when to call ensureIndex?

后端 未结 7 1026
囚心锁ツ
囚心锁ツ 2021-02-01 01:34

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

Regards,

Johnny

7条回答
  •  不要未来只要你来
    2021-02-01 02:25

    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());
        // ...
    }
    

提交回复
热议问题