Update _id field in MongoDB

MongoDBDatabaseBig Data Analytics

To update, just save new ID and remove the old one using remove(). Let us first create a collection with documents −

> db.updatingDemo.insertOne({"StudentName":"Robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e04dae5150ee0e76c06a04b")
}
> db.updatingDemo.insertOne({"StudentName":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e04dae7150ee0e76c06a04c")
}

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

> db.updatingDemo.find();

This will produce the following output −

{ "_id" : ObjectId("5e04dae5150ee0e76c06a04b"), "StudentName" : "Robert" }
{ "_id" : ObjectId("5e04dae7150ee0e76c06a04c"), "StudentName" : "Bob" }

Here is the query to update _id in MongoDB −

> myDocument = db.updatingDemo.findOne({"StudentName":"Bob"});
{ "_id" : ObjectId("5e04dae7150ee0e76c06a04c"), "StudentName" : "Bob" }
> myDocument._id = 1001;
1001
> db.updatingDemo.insert(myDocument);
WriteResult({ "nInserted" : 1 })
> db.updatingDemo.remove({_id:ObjectId("5e04dae7150ee0e76c06a04c")});
WriteResult({ "nRemoved" : 1 })

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

> db.updatingDemo.find();

This will produce the following output −

{ "_id" : ObjectId("5e04dae5150ee0e76c06a04b"), "StudentName" : "Robert" }
{ "_id" : 1001, "StudentName" : "Bob" }
raja
Published on 27-Mar-2020 16:37:45
Advertisements