MongoDB Query to Update Field and Modify Data in Column



For this, use find() along with update(). Let us create a collection with documents −

> db.demo115.insertOne({"LastName":"Brown"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2efe9bd8f64a552dae635a")
}

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

> db.demo115.find();

This will produce the following output −

{ "_id" : ObjectId("5e2efe9bd8f64a552dae635a"), "LastName" : "Brown" }

Following is the query to update field and modify the data currently in column −

> db.demo115.find({"LastName":"Brown"}).forEach(function(d) {
... db.demo115.update({_id: d._id}, {$set: {LastName: 'Hello ' + d.LastName}});
... })

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

> db.demo115.find();

This will produce the following output −

{ "_id" : ObjectId("5e2efe9bd8f64a552dae635a"), "LastName" : "Hello Brown" }
Updated on: 2020-03-30T12:08:25+05:30

427 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements