Computer >> Computer tutorials >  >> Programming >> MongoDB

Updating sub-object in MongoDB?


You can use $set operator for this. Let us first create a collection with documents −

> db.updateSubObjectDemo.insertOne(
...    {
...
...       "ClientId" : 100,
...       "ClientDetails" : {
...          "ClientFirstName" : "Adam"
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd31434b64f4b851c3a13e9")
}

Following is the query to display all documents from a collection with the help of find() method −

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

This will produce the following output −

{
   "_id" : ObjectId("5cd31434b64f4b851c3a13e9"),
   "ClientId" : 100,
   "ClientDetails" : {
      "ClientFirstName" : "Adam"
   }
}

Following is the query to update sub-object in MongoDB. Here, we have set ClientLastName −

> db.updateSubObjectDemo.update({ClientId : 100}, { $set : { "ClientDetails.ClientLastName" : "Smith"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us display all documents from the above collection −

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

This will produce the following output −

{
   "_id" : ObjectId("5cd31434b64f4b851c3a13e9"),
   "ClientId" : 100,
   "ClientDetails" : {
      "ClientFirstName" : "Adam",
      "ClientLastName" : "Smith"
   }
}