MongoDB query to update nested document



Let us create a collection with documents −

> db.demo595.insertOne( { "Information": [    { "_id": new ObjectId(), Name:"Chris" },    { _id:new ObjectId(), Name:"Robert" } ] } ); {    "acknowledged" : true,    "insertedId" : ObjectId("5e93369cfd2d90c177b5bce4") }

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

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

This will produce the following output −

{    "_id" : ObjectId("5e93369cfd2d90c177b5bce4"),    "Information" : [       {          "_id" : ObjectId("5e93369cfd2d90c177b5bce2"),          "Name" : "Chris"       },       {          "_id" : ObjectId("5e93369cfd2d90c177b5bce3"),          "Name" : "Robert"       }    ] }

Following is the query to update nested document −

>db.demo595.update({"Information._id":ObjectId("5e93369cfd2d90c177b5bce2")},    {$set:{"Info rmation.$.Name":"David Miller"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

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

This will produce the following output −

{    "_id" : ObjectId("5e93369cfd2d90c177b5bce4"),    "Information" : [       {          "_id" : ObjectId("5e93369cfd2d90c177b5bce2"),          "Name" : "David Miller"       },       {          "_id" : ObjectId("5e93369cfd2d90c177b5bce3"),          "Name" : "Robert"       }    ] }
Updated on: 2020-05-15T07:01:00+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements