如何在 MongoDB 中创建索引?
要创建 MongoDB 中的索引,请使用 ensureIndex() 方法。我们首先使用以下查询创建一个集合
> db.createCollection(&qu/ot;creatingUniqueIndexDemo"); { "ok" : 1 }
以下是针对上述集合创建索引的查询
> db.creatingUniqueIndexDemo.ensureIndex({"UserCountryName":1},{unique:true}); { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
以下是向上述集合中插入一些文档的查询
>db.creatingUniqueIndexDemo.insertOne({"UserName":"John","UserAge":21,"UserCountryName":"US"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9947bd330fd0aa0d2fe4d8") } >db.creatingUniqueIndexDemo.insertOne({"UserName":"Mike","UserAge":23,"UserCountryName":"UK"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9947c9330fd0aa0d2fe4d9") } >db.creatingUniqueIndexDemo.insertOne({"UserName":"Robert","UserAge":26,"UserCountryName":"US"}); 2019-03-26T02:57:52.670+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: test.creatingUniqueIndexDemo index: UserCountryName_1 dup key: { : "US" } : WriteError({ "index" : 0, "code" : 11000, "errmsg" : "E11000 duplicate key error collection: test.creatingUniqueIndexDemo index: . UserCountryName_1 dup key: { : \"US\" }", "op" : { "_id" : ObjectId("5c9947d8330fd0aa0d2fe4da"), "UserName" : "Robert", "UserAge" : 26, "UserCountryName" : "US" } }) 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.creatingUniqueIndexDemo.insertOne({"UserName":"Robert","UserAge":26,"UserCountryName":"AUS"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9947e3330fd0aa0d2fe4db") }
以下是使用 find() 方法从集合中显示所有文档的查询
> db.creatingUniqueIndexDemo.find().pretty();
这将生成以下输出
{ "_id" : ObjectId("5c9947bd330fd0aa0d2fe4d8"), "UserName" : "John", "UserAge" : 21, "UserCountryName" : "US" } { "_id" : ObjectId("5c9947c9330fd0aa0d2fe4d9"), "UserName" : "Mike", "UserAge" : 23, "UserCountryName" : "UK" } { "_id" : ObjectId("5c9947e3330fd0aa0d2fe4db"), "UserName" : "Robert", "UserAge" : 26, "UserCountryName" : "AUS" }
广告