Updating MongoDB collection for _id?

MongoDBDatabaseBig Data Analytics

To update for _id, use $set in MongoDB. Let us create a collection with documents −

db.demo741.insertOne({SubjectName:"MySQL"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ead718657bb72a10bcf0672")
}
> db.demo741.insertOne({SubjectName:"C"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ead718957bb72a10bcf0673")
}
> db.demo741.insertOne({SubjectName:"Java"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ead718e57bb72a10bcf0674")
}

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

> db.demo741.find();

This will produce the following output −

{ "_id" : ObjectId("5ead718657bb72a10bcf0672"), "SubjectName" : "MySQL" }
{ "_id" : ObjectId("5ead718957bb72a10bcf0673"), "SubjectName" : "C" }
{ "_id" : ObjectId("5ead718e57bb72a10bcf0674"), "SubjectName" : "Java" }

Following is the query to updating MongoDB for _id −

>db.demo741.update({_id:ObjectId("5ead718957bb72a10bcf0673")},{$set:{SubjectName:"PL/SQL"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo741.find();

This will produce the following output −

{ "_id" : ObjectId("5ead718657bb72a10bcf0672"), "SubjectName" : "MySQL" }
{ "_id" : ObjectId("5ead718957bb72a10bcf0673"), "SubjectName" : "PL/SQL" }
{ "_id" : ObjectId("5ead718e57bb72a10bcf0674"), "SubjectName" : "Java" }
raja
Published on 30-Jun-2020 11:26:32
Advertisements