How to update array with multiple conditions in MongoDB

MongoDBDatabaseBig Data Analytics

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" : [ ] }
   ] 
}
raja
Published on 30-Mar-2020 13:02:21
Advertisements