MongoDB transaction & indexes for duplicate values


Use ensureIndex() and set unique:1 inside the array. Let us create a collection with documents −

> db.demo298.save({Name: 'Chris', Marks: [46, 79] });
WriteResult({ "nInserted" : 1 })
> db.demo298.save({Name: 'David', Marks: [67, 88] });
WriteResult({ "nInserted" : 1 })
> db.demo298.ensureIndex({ Marks: 1 }, {unique: 1});
{
   "createdCollectionAutomatically" : false,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}
> db.demo298.save({Name: 'Mike', Marks: [88,98] });
WriteResult({
   "nInserted" : 0,
   "writeError" : {
      "code" : 11000,
      "errmsg" : "E11000 duplicate key error collection: test.demo298 index: Marks_1 dup key: { : 88.0 }"
   }
})

Display all documents from a collection with the help of find() method −

> db.demo298.find();

This will produce the following output −

{ "_id" : ObjectId("5e4d56e55d93261e4bc9ea48"), "Name" : "Chris", "Marks" : [ 46, 79 ] }
{ "_id" : ObjectId("5e4d56f55d93261e4bc9ea49"), "Name" : "David", "Marks" : [ 67, 88 ] }

Updated on: 01-Apr-2020

194 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements