Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to update array with multiple conditions in MongoDB
To update array with multiple conditions in MongoDB, use $elemMatch to match array elements with specific criteria, combined with $push and the positional operator $ to add new elements to the matched array element.
Syntax
db.collection.updateOne(
{ "arrayField": { "$elemMatch": { "field1": "value1", "field2": "value2" } } },
{ "$push": { "arrayField.$.targetField": newValue } }
);
Sample Data
db.demo94.insertOne({
"Details": [
{
"Name": "Chris",
"Subject": []
},
{
"Name": "David",
"Subject": []
},
{
"Name": "Bob",
"Subject": []
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e2d553bb8903cdd865577a9")
}
Example: Update Array Element with Multiple Conditions
Add a subject to David's Subject array using $elemMatch to locate the specific array element ?
db.demo94.updateOne(
{
"Details": { "$elemMatch": { "Name": "David" } }
},
{
"$push": { "Details.$.Subject": { "Subject": "MongoDB" } }
}
);
{ "acknowledged": true, "matchedCount": 1, "modifiedCount": 1 }
Verify Result
db.demo94.find();
{
"_id": ObjectId("5e2d553bb8903cdd865577a9"),
"Details": [
{ "Name": "Chris", "Subject": [] },
{ "Name": "David", "Subject": [{ "Subject": "MongoDB" }] },
{ "Name": "Bob", "Subject": [] }
]
}
Key Points
-
$elemMatchfinds the first array element matching all specified conditions. - The positional operator
$refers to the matched array element's position. -
$pushadds new elements to the targeted nested array.
Conclusion
Use $elemMatch with the positional operator $ to update specific array elements based on multiple conditions. This approach ensures precise targeting of nested array elements for updates.
Advertisements
