注意从mongoDB 3.0开始ensureIndex被废弃,今后都仅仅是db.collection.createIndex的一个别名。
dbDao 百度贴吧:http://tieba.baidu.com/dbdao
MongoDB技术学习QQ群: 421431253
db.collection.createIndex主要分成2部分: KEY和OPTION。
KEY:
> db.dbdao_product.ensureIndex({x:1}); { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.dbdao_product.find({x:200}); { "_id" : ObjectId("5524face073d738e116afc2c"), "x" : 200, "name" : "askmaclean.com", "name1" : "askmaclean.com", "name2" : "askmaclean.com", "name3" : "askmaclean.com" } { "_id" : ObjectId("5524face073d738e116afc2d"), "x" : 200, "name" : "askmaclean.com", "name1" : "askmaclean.com", "name2" : "askmaclean.com", "name3" : "askmaclean.com" } > > db.dbdao_product.find({x:200}).explain(); { "queryPlanner" : { "plannerVersion" : 1, "namespace" : "test.dbdao_product", "indexFilterSet" : false, "parsedQuery" : { "x" : { "$eq" : 200 } }, "winningPlan" : { "stage" : "FETCH", "inputStage" : { "stage" : "IXSCAN", "keyPattern" : { "x" : 1 }, "indexName" : "x_1", "isMultiKey" : false, "direction" : "forward", "indexBounds" : { "x" : [ "[200.0, 200.0]" ] } } }, "rejectedPlans" : [ ] }, "serverInfo" : { "host" : "dbdao-Inspiron-560s", "port" : 27017, "version" : "3.0.2", "gitVersion" : "6201872043ecbbc0a4cc169b5482dcf385fc464f" }, "ok" : 1 }
dropDups 参数在mongodb 3.0.2中被废弃, 该参数的用意是在创建unique的索引时若遇到duplicate重复document,则仅仅保持_ID最小的哪一个document:
A unique index cannot be created on a key that has duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate values, add the dropDups option.
例如
MongoDB shell version: 3.0.2 connecting to: test > db.dupme.insert({x:1,y:1}); WriteResult({ "nInserted" : 1 }) > db.dupme.insert({x:1,y:1}); WriteResult({ "nInserted" : 1 }) > db.dupme.insert({x:1,y:1}); WriteResult({ "nInserted" : 1 }) > db.dupme.insert({x:1,y:1}); WriteResult({ "nInserted" : 1 }) > > db.dupme.find(); { "_id" : ObjectId("552524627501a28814fdddc7"), "x" : 1, "y" : 1 } { "_id" : ObjectId("552524637501a28814fdddc8"), "x" : 1, "y" : 1 } { "_id" : ObjectId("552524657501a28814fdddc9"), "x" : 1, "y" : 1 } { "_id" : ObjectId("552524667501a28814fdddca"), "x" : 1, "y" : 1 } > > db.dupme.ensureIndex({x:1},{unique:true, dropDups:true}); { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "errmsg" : "exception: E11000 duplicate key error collection: test.dupme index: x_1 dup key: { : 1.0 }", "code" : 11000, "ok" : 0 } > db.dupme.ensureIndex({x:1},{unique:true, dropDups:true}); { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "errmsg" : "exception: E11000 duplicate key error collection: test.dupme index: x_1 dup key: { : 1.0 }", "code" : 11000, "ok" : 0 }
以上由于我们测试的版本是mongodb 3.0.2,所以直接忽略了dropDups参数。