How to update array with multiple conditions in MongoDB


To update array with multiple conditions, use $push in MongoDB. Let us create a collection with documents −

> db.demo94.insertOne(
... {
...
...    "Details" : [
...       {
...          "Name" : "Chris",
...          "Subject" : []
...       },
...       {
...          "Name" : "David",
...          "Subject" : []
...       },
...       {
...          "Name" : "Bob",
...          "Subject" : []
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2d553bb8903cdd865577a9")
}

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

> db.demo94.find();

This will produce the following output −

{
   "_id" : ObjectId("5e2d553bb8903cdd865577a9"), "Details" : [
      { "Name" : "Chris", "Subject" : [ ] },
      { "Name" : "David", "Subject" : [ ] }, { "Name" : "Bob", "Subject" : [ ] }
   ]
}

Following is the query to update array with multiple conditions in MongoDB −

> db.demo94.updateOne(
... {
...
...    "Details": { "$elemMatch": { "Name": "David"}}
... },
... {
...    "$push": { "Details.$.Subject": { "Subject": "MongoDB" }}
... }
...);
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

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

> db.demo94.find();

This will produce the following output −

{
   "_id" : ObjectId("5e2d553bb8903cdd865577a9"), "Details" : [
      { "Name" : "Chris", "Subject" : [ ] },
      { "Name" : "David", "Subject" : [ { "Subject" : "MongoDB" } ] },
      { "Name" : "Bob", "Subject" : [ ] }
   ] 
}

Updated on: 30-Mar-2020

568 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements