Upsert in MongoDB while using custom _id values to insert a document if it does not exist?

MongoDBDatabaseBig Data Analytics

You need to use insert() for this. Whenever you insert custom _id values and the document already exist with the custom _id value then an error is visible. 

Let us first create a collection with documents. Under this, we tried adding the same document again and this resulted in an error

> db.customIdDemo.insert({"_id":1,"StudentName":"John"});
WriteResult({ "nInserted" : 1 })
> db.customIdDemo.insert({"_id":1,"StudentName":"Carol"});
WriteResult({
   "nInserted" : 0,
   "writeError" : {
      "code" : 11000,
      "errmsg" : "E11000 duplicate key error collection: admin.customIdDemo index: _id_ dup key: { : 1.0 }"
   }
})
> db.customIdDemo.insert({"_id":2,"StudentName":"Carol"});
WriteResult({ "nInserted" : 1 })
> db.customIdDemo.insert({"_id":2,"StudentName":"Carol"});
WriteResult({
   "nInserted" : 0,
   "writeError" : {
      "code" : 11000,
      "errmsg" : "E11000 duplicate key error collection: admin.customIdDemo index: _id_ dup key: { : 2.0 }"
   }
})
> db.customIdDemo.insert({"_id":3,"StudentName":"Chris"});
WriteResult({ "nInserted" : 1 })

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

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

This will produce the following output

{ "_id" : 1, "StudentName" : "John" }
{ "_id" : 2, "StudentName" : "Carol" }
{ "_id" : 3, "StudentName" : "Chris" }
raja
Published on 11-Apr-2019 14:47:51
Advertisements