Insert in MongoDB without duplicates


To insert records in MongoDB and avoid duplicates, use “unique:true”. Let us first create a collection with documents.

Here, we are trying to add duplicate records −

> db.insertWithoutDuplicateDemo.createIndex({"StudentFirstName":1},{ unique: true } );
{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}
> db.insertWithoutDuplicateDemo.insert({"StudentFirstName":"Chris"},{ upsert: true });
WriteResult({ "nInserted" : 1 })
> db.insertWithoutDuplicateDemo.insert({"StudentFirstName":"David"},{ upsert: true });
WriteResult({ "nInserted" : 1 })
> db.insertWithoutDuplicateDemo.insert({"StudentFirstName":"Chris"},{ upsert: true });
WriteResult({
   "nInserted" : 0,
   "writeError" : {
      "code" : 11000,
      "errmsg" : "E11000 duplicate key error collection: test.insertWithoutDuplicateDemo index:             StudentFirstName_1 dup key: { : \"Chris\" }"
   }
})
> db.insertWithoutDuplicateDemo.insert({"StudentFirstName":"Bob"},{ upsert: true });
WriteResult({ "nInserted" : 1 })

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e064405150ee0e76c06a054"),
   "StudentFirstName" : "Chris"
}
{
   "_id" : ObjectId("5e064410150ee0e76c06a055"),
   "StudentFirstName" : "David"
}
{ "_id" : ObjectId("5e06441f150ee0e76c06a057"), "StudentFirstName" : "Bob" }

Updated on: 27-Mar-2020

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements