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 push new items to an array inside of an object in MongoDB?
To push new items to an array inside of an object in MongoDB, use the $push operator combined with the $elemMatch operator to match the specific object, then use the $ positional operator to target the array field.
Syntax
db.collection.update(
{
"_id": documentId,
"arrayField": { "$elemMatch": { "matchField": "matchValue" } }
},
{
"$push": { "arrayField.$.targetArray": "newValue" }
}
);
Sample Data
Let us create a collection with documents ?
db.pushNewItemsDemo.insertOne({
"_id": 1,
"StudentScore": 56,
"StudentOtherDetails": [
{
"StudentName": "John",
"StudentFriendName": ["Bob", "Carol"]
},
{
"StudentName": "David",
"StudentFriendName": ["Mike", "Sam"]
}
]
});
{ "acknowledged": true, "insertedId": 1 }
Display the document to verify the data ?
db.pushNewItemsDemo.find();
{
"_id": 1,
"StudentScore": 56,
"StudentOtherDetails": [
{ "StudentName": "John", "StudentFriendName": ["Bob", "Carol"] },
{ "StudentName": "David", "StudentFriendName": ["Mike", "Sam"] }
]
}
Example: Push Item to Nested Array
Push "James" to David's StudentFriendName array ?
db.pushNewItemsDemo.update(
{
"_id": 1,
"StudentOtherDetails": { "$elemMatch": { "StudentName": "David" } }
},
{
"$push": { "StudentOtherDetails.$.StudentFriendName": "James" }
}
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
db.pushNewItemsDemo.find();
{
"_id": 1,
"StudentScore": 56,
"StudentOtherDetails": [
{ "StudentName": "John", "StudentFriendName": ["Bob", "Carol"] },
{ "StudentName": "David", "StudentFriendName": ["Mike", "Sam", "James"] }
]
}
How It Works
-
$elemMatchfinds the object in the array that matches the condition (StudentName: "David") -
$positional operator identifies the matched array element's position -
$pushadds the new value to the specified nested array field
Conclusion
Use $elemMatch to match objects within arrays, then combine $push with the $ positional operator to add new items to nested arrays. This approach ensures you update the correct object's array field.
Advertisements
