How to keep two “columns” in MongoDB unique?

MongoDBDatabaseBig Data Analytics

Use unique and set it to TRUE. Let us implement the same by creating index and setting two columns to unique −

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

Now you can insert documents in the above collection −

>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

Above, since we set the two columns unique and now we are trying to include duplicate values, the following error is visible −

duplicate key error collection

Following is the query to display all documents from a collection with the help of find() method −

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

This will produce the following output −

{
   "_id" : ObjectId("5cd30fd7b64f4b851c3a13e5"),
   "StudentFirstName" : "John",
   "StudentLastName" : "Smith",
   "StudentAge" : 21
}
{
   "_id" : ObjectId("5cd30fe5b64f4b851c3a13e6"),
   "StudentFirstName" : "John",
   "StudentLastName" : "Doe",
   "StudentAge" : 23
}
raja
Published on 22-May-2019 12:15:05
Advertisements