How to update _id field in MongoDB?


You can’t directly update _id field i.e. write some script to update. Let us first create a collection with documents −

> db.updatingIdFieldDemo.insertOne({"StudentName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce271bb36e8b255a5eee949")
}

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

> db.updatingIdFieldDemo.find();

This will produce the following output −

{ "_id" : ObjectId("5ce271bb36e8b255a5eee949"), "StudentName" : "Chris" }

Following is the query to update _id field in MongoDB −

> var myDocument=db.updatingIdFieldDemo.findOne({StudentName:"Chris"});
> myDocument._id = 101;
101
> db.updatingIdFieldDemo.save(myDocument);
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 101 })

> db.updatingIdFieldDemo.remove({_id:ObjectId("5ce271bb36e8b255a5eee949")});
WriteResult({ "nRemoved" : 1 })

Let us check the records once again −

> db.updatingIdFieldDemo.find();

This will produce the following output. We have successfully updated _id −

{ "_id" : 101, "StudentName" : "Chris" }

Updated on: 30-Jul-2019

223 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements