如何在 MongoDB 中创建唯一字段?
若要在 MongoDB 中创建唯一字段,请使用 unique-true。让我们创建一个包含文档的集合-
> db.demo82.createIndex({"EmployeeName":1},{unique:true}); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.demo82.insertOne({"EmployeeName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e2bfb1b71bf0181ecc422a0") } > db.demo82.insertOne({"EmployeeName":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e2bfb1f71bf0181ecc422a1") } > db.demo82.insertOne({"EmployeeName":"Chris"}); 2020-01-25T13:54:00.410+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: test.demo82 index: EmployeeName_1 dup key: { : "Chris" } : WriteError({ "index" : 0, "code" : 11000, "errmsg" : "E11000 duplicate key error collection: test.demo82 index: EmployeeName_1 dup key: { : \"Chris\" }", "op" : { "_id" : ObjectId("5e2bfb2071bf0181ecc422a2"), "EmployeeName" : "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.demo82.find();
这将产生以下输出。由于我们上面使用了 unique-true,因此不会插入重复的值-
{ "_id" : ObjectId("5e2bfb1b71bf0181ecc422a0"), "EmployeeName" : "Chris" } { "_id" : ObjectId("5e2bfb1f71bf0181ecc422a1"), "EmployeeName" : "David" }
广告