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

MongoDBDatabaseBig Data Analytics

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" }
raja
Published on 30-Apr-2019 14:27:43
Advertisements