要在MongoDB中设置唯一索引,请使用unique:true。让我们创建一个包含文档的集合-
> db.demo257.ensureIndex({Name:1},{unique:true}); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.demo257.insertOne({Name:"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e47a5e51627c0c63e7dba91") } > db.demo257.insertOne({Name:"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e47a5e81627c0c63e7dba92") } > db.demo257.insertOne({Name:"Chris"}); 2020-02-15T13:33:54.064+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: test.demo257 index: Name_1 dup key: { : "Chris" } : WriteError({ "index" : 0, "code" : 11000, "errmsg" : "E11000 duplicate key error collection: test.demo257 index: Name_1 dup key: { : \"Chris\" }", "op" : { "_id" : ObjectId("5e47a5ea1627c0c63e7dba93"), "Name" : "Chris" } }) 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.demo257.find();
这将产生以下输出-
{ "_id" : ObjectId("5e47a5e51627c0c63e7dba91"), "Name" : "Chris" } { "_id" : ObjectId("5e47a5e81627c0c63e7dba92"), "Name" : "Bob" }