MongoDB query to update tag


To update tag in MongoDB, use the update command. Let us create a collection with documents −

> db.demo713.insertOne(
... {
... tags:
...    [
...       {
...          id:101,
...          Name:"Tag-1"
...       },
...       {
...          id:102,
...          Name:"Tag-3"
...       },
...       {
...          id:103,
...          Name:"Tag-3"
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea8625a5d33e20ed1097b87")
}

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

> db.demo713.find();

This will produce the following output −

{ "_id" : ObjectId("5ea8625a5d33e20ed1097b87"), "tags" : [ { "id" : 101, "Name" : "Tag-1" }, {
"id" : 102, "Name" : "Tag-3" }, { "id" : 103, "Name" : "Tag-3" } ] }

Following is the query to update tag −

> db.demo713.update({"tags.id":102},{$set:{"tags.$.Name":"Tag-2"}},false,true);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

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

This will produce the following output −

{
   "_id" : ObjectId("5ea8625a5d33e20ed1097b87"),
   "tags" : [
      {
         "id" : 101,
         "Name" : "Tag-1"
      },
      {
         "id" : 102,
         "Name" : "Tag-2"
      },
      {
         "id" : 103,
         "Name" : "Tag-3"
      }
   ]
}

Updated on: 11-May-2020

187 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements