使用固定值字段设置MongoDB复合索引
为此,我们将使用createIndex()
和创建索引的概念-
> db.compoundIndexDemo.createIndex({"StudentName":1,"StudentAge":1},{unique:true}); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
首先让我们创建一个包含文档的集合-
> db.compoundIndexDemo.insertOne({"StudentName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e084c1d25ddae1f53b62207") } > db.compoundIndexDemo.insertOne({"StudentName":"Chris","StudentAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5e084c5625ddae1f53b62209") } > db.compoundIndexDemo.insertOne({"StudentName":"Chris","StudentAge":22}); { "acknowledged" : true, "insertedId" : ObjectId("5e084c5b25ddae1f53b6220a") } > db.compoundIndexDemo.insertOne({"StudentName":"Chris","StudentAge":23}); 2019-12-29T12:19:02.225+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: web.compoundIndexDemo index: StudentName_1_StudentAge_1 dup key: { : "Chris", : 23.0 } : WriteError({ "index" : 0, "code" : 11000, "errmsg" : "E11000 duplicate key error collection: web.compoundIndexDemo index: StudentName_1_StudentAge_1 dup key: { : \"Chris\", : 23.0 }", "op" : { "_id" : ObjectId("5e084c5e25ddae1f53b6220b"), "StudentName" : "Chris", "StudentAge" : 23 } }) WriteError@src/mongo/shell/bulk_api.js:461:48 Bulk/mergeBatchResults@src/mongo/shell/bulk_api.js:841:49 Bulk/executeBatch@src/mongo/shell/bulk_api.js:906:13 Bulk/this.execute@src/mongo/shell/bulk_api.js:1150:21 DBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:252:9 @(shell):1:1
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.compoundIndexDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5e084c1d25ddae1f53b62207"), "StudentName" : "Chris" } { "_id" : ObjectId("5e084c5625ddae1f53b62209"), "StudentName" : "Chris", "StudentAge" : 23 } { "_id" : ObjectId("5e084c5b25ddae1f53b6220a"), "StudentName" : "Chris", "StudentAge" : 22 }