Saturday, October 17, 2020

Mongo DB - Updating Documents

In this article we will see how to update data in Mongo DB collections.

For updating a single record, the following update query can be used. Note that this query has two parts inside the update() method. The first part is for filtering the documents that have to be updated. While the second part is the target attribute and value that has to be updated.

db.Books.update({_id: ObjectId("1234d4ef422drf433rffer4d2445f43")}, {$set: {title: "Learning"}});

For updating multiple records, the following update query can be used. Note that this query has three parts inside the update() method. The first part is for filtering the documents that have to be updated. While the second part is the target attribute and value that has to be updated. The third part is important to explicitly specify that this query will affect multiple documents - by default this is set to false.

db.Books.update({author: /Anonymous/}, {$set: {author: "Anon"}}, {multi: true});

Hope you find this crisp and useful.

Cheers!

No comments:

Post a Comment