如何在 MongoDB 中保持两“列”的唯一性?


使用 unique 并将其设置为 TRUE。我们通过创建索引并将两列设置为 unique 来实现此目标,如下所示 −

>db.keepTwoColumnsUniqueDemo.createIndex({"StudentFirstName":1,"StudentLastName":1},{unique:true});
{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}

现在可以在上述集合中插入文档 −

>db.keepTwoColumnsUniqueDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Smith","StudentAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd30fd7b64f4b851c3a13e5")
}
>db.keepTwoColumnsUniqueDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Doe","StudentAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd30fe5b64f4b851c3a13e6")
}
>db.keepTwoColumnsUniqueDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Smith","StudentAge":24});
2019-05-08T22:50:42.803+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: sample.keepTwoColumnsUniqueDemo index: StudentFirstName_1_StudentLastName_1 dup key: { : "John", : "Smith" } :
WriteError({
"index" : 0,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: sample.keepTwoColumnsUniqueDemo index: StudentFirstName_1_StudentLastName_1 dup key: { : \"John\", : \"Smith\" }",
"op" : {
"_id" : ObjectId("5cd30feab64f4b851c3a13e7"),
"StudentFirstName" : "John",
"StudentLastName" : "Smith",
"StudentAge" : 24
}
})
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

由于上面我们设置了两列为 unique,现在我们尝试包含重复值,因此会显示以下错误 −

duplicate key error collection

以下是使用 find() 方法从集合中显示所有文档的查询 −

> db.keepTwoColumnsUniqueDemo.find().pretty();

将生成以下输出 −

{
   "_id" : ObjectId("5cd30fd7b64f4b851c3a13e5"),
   "StudentFirstName" : "John",
   "StudentLastName" : "Smith",
   "StudentAge" : 21
}
{
   "_id" : ObjectId("5cd30fe5b64f4b851c3a13e6"),
   "StudentFirstName" : "John",
   "StudentLastName" : "Doe",
   "StudentAge" : 23
}

更新时间:30-7-2019

823 次浏览

启动您的 职业生涯

完成课程获得认证

开始
广告