MongoDB 索引 - 是否可以同时创建普通索引和复合索引?
是的,你可以使用 ensureIndex()。MongoDB 为文档集合中的任何字段提供索引的完全支持。
让我们创建一个包含文档的集合 −
> db.demo622.ensureIndex({_id:1,Name:1,Age:1}); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.demo622.insertOne({_id:101,Name:"Chris",Age:21}); { "acknowledged" : true, "insertedId" : 101 } > db.demo622.insertOne({_id:102,Name:"Chris",Age:22}); { "acknowledged" : true, "insertedId" : 102 } > db.demo622.insertOne({_id:103,Name:"Bob",Age:21}); { "acknowledged" : true, "insertedId" : 103 } > db.demo622.insertOne({_id:104,Name:"Chris",Age:22}); { "acknowledged" : true, "insertedId" : 104 } > db.demo622.insertOne({_id:104,Name:"Chris",Age:22}); 2020-04-18T12:21:18.085+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: test.demo622 index: _id_ dup key: { : 104.0 } : WriteError({ "index" : 0, "code" : 11000, "errmsg" : "E11000 duplicate key error collection: test.demo622 index: _id_ dup key: { : 104.0 }", "op" : { "_id" : 104, "Name" : "Chris", "Age" : 22 } }) 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 > db.demo622.insertOne({_id:105,Name:"Chris",Age:22}); { "acknowledged" : true, "insertedId" : 105 }
使用 find() 方法显示集合中的所有文档 −
> db.demo622.find();
这将生成以下输出 −
{ "_id" : 101, "Name" : "Chris", "Age" : 21 } { "_id" : 102, "Name" : "Chris", "Age" : 22 } { "_id" : 103, "Name" : "Bob", "Age" : 21 } { "_id" : 104, "Name" : "Chris", "Age" : 22 } { "_id" : 105, "Name" : "Chris", "Age" : 22 }
广告