MongoDB query to update nested document

MongoDBDatabaseBig Data Analytics

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"
      }
   ]
}
raja
Published on 15-May-2020 10:29:37
Advertisements