How to update record in MongoDB without replacing the existing fields?


You can use $set operator for this Let us first create a collection with documents −

> db.updateRecordDemo.insertOne({"StudentName":"Larry"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbd6f95de8cc557214c0e0a")
}
> db.updateRecordDemo.insertOne({"StudentName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbd6f9cde8cc557214c0e0b")
}
> db.updateRecordDemo.insertOne({"StudentName":"Mike"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbd6f9dde8cc557214c0e0c")
}

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

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

This will produce the following output −

{ "_id" : ObjectId("5cbd6f95de8cc557214c0e0a"), "StudentName" : "Larry" }
{ "_id" : ObjectId("5cbd6f9cde8cc557214c0e0b"), "StudentName" : "David" }
{ "_id" : ObjectId("5cbd6f9dde8cc557214c0e0c"), "StudentName" : "Mike" }

Following is the query to update record in MongoDB without replacing the existing fields −

> db.updateRecordDemo.update({"_id" :ObjectId("5cbd6f9cde8cc557214c0e0b") },{$set : {"StudentAge":24}});
   WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us Display all documents from the collection once again −

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

This will produce the following output −

{ "_id" : ObjectId("5cbd6f95de8cc557214c0e0a"), "StudentName" : "Larry" }
{
   "_id" : ObjectId("5cbd6f9cde8cc557214c0e0b"),
   "StudentName" : "David",
   "StudentAge" : 24
}
{ "_id" : ObjectId("5cbd6f9dde8cc557214c0e0c"), "StudentName" : "Mike" }

Updated on: 30-Jul-2019

301 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements