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

使用唯一并将其设置为TRUE。让我们通过创建索引并将两列设置为唯一来实现相同-

>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

上面,由于我们将两列设置为唯一,并且现在我们试图包括重复值,因此可以看到以下错误-

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
}