Manipulating subdocuments in MongoDB


To manipulate subdocuments, use dot(.) notation in MongoDB. Let us first create a collection with documents −

> db.demo378.insertOne(
...    {
...       Name: 'Chris',
...       details:[
...          {id:101,Score:56},
...          {id:102,Score:78}
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5a758a2ae06a1609a00b0f")
}

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

> db.demo378.find();

This will produce the following output −

{
   "_id" : ObjectId("5e5a758a2ae06a1609a00b0f"), "Name" : "Chris", "details" : [
      { "id" : 101, "Score" : 56 }, { "id" : 102, "Score" : 78 }
   ]
}

Following is the query to manipulate subdocuments −

> db.demo378.update({Name: "Chris", "details.id":102 }, { $inc: { "details.$.Score": -8 } });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo378.find();

This will produce the following output −

{
   "_id" : ObjectId("5e5a758a2ae06a1609a00b0f"), "Name" : "Chris", "details" : [
      { "id" : 101, "Score" : 56 }, { "id" : 102, "Score" : 70 }
   ] 
}

Updated on: 02-Apr-2020

128 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements