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
MongoDB query to insert an array element with a condition?
To insert an array element with a condition in MongoDB, use the $push operator combined with the $ positional operator to add new elements to nested arrays when specific conditions are met.
Syntax
db.collection.update(
{"arrayField.conditionField": "value"},
{$push: {"arrayField.$.targetArray": newElement}}
);
Sample Data
db.demo11.insertOne({
"ListOfStudent": [
{
"StudentName": "Chris",
"ListOfScore": [76, 67, 54, 89]
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e0f6e34d7df943a7cec4fa1")
}
Example: Add Score with Student Name Condition
Insert a new score (98) to Chris's ListOfScore array ?
db.demo11.update(
{"ListOfStudent.StudentName": "Chris"},
{$push: {"ListOfStudent.$.ListOfScore": 98}}
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
db.demo11.find().pretty();
{
"_id": ObjectId("5e0f6e34d7df943a7cec4fa1"),
"ListOfStudent": [
{
"StudentName": "Chris",
"ListOfScore": [
76,
67,
54,
89,
98
]
}
]
}
Key Points
- The
$positional operator identifies the first array element matching the query condition. -
$pushadds the new element to the end of the specified nested array. - Use dot notation to navigate through nested document structures.
Conclusion
Combine $push with the $ positional operator to conditionally insert elements into nested arrays. This approach ensures you target the correct array element based on your specified criteria.
Advertisements
