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
MongoDB $push in nested array?
The $push operator adds elements to an array field. To push into a nested array (an array inside another array), use the $ positional operator to identify the matched parent array element, then target the nested array with dot notation.
Sample Data
db.nestedArrayDemo.insertOne({
"EmployeeName": "Larry",
"EmployeeSalary": 9000,
"EmployeeDetails": [{
"EmployeeDOB": new Date("1990-01-21"),
"EmployeeDepartment": "ComputerScience",
"EmployeeProject": [
{"Technology": "C", "Duration": 6},
{"Technology": "Java", "Duration": 7}
]
}]
});
Push into Nested Array
Add a new project to the EmployeeProject array inside EmployeeDetails ?
db.nestedArrayDemo.update(
{
"_id": ObjectId("5c6d73090c3d5054b766a76e"),
"EmployeeDetails.EmployeeDepartment": "ComputerScience"
},
{
$push: {
"EmployeeDetails.$.EmployeeProject": {
"Technology": "Python",
"Duration": 4
}
}
}
);
The $ in EmployeeDetails.$ refers to the first element in EmployeeDetails that matches EmployeeDepartment: "ComputerScience". Then .EmployeeProject targets the nested array within that matched element.
Verify Result
db.nestedArrayDemo.find().pretty();
{
"EmployeeName": "Larry",
"EmployeeSalary": 9000,
"EmployeeDetails": [{
"EmployeeDOB": ISODate("1990-01-21T00:00:00Z"),
"EmployeeDepartment": "ComputerScience",
"EmployeeProject": [
{"Technology": "C", "Duration": 6},
{"Technology": "Java", "Duration": 7},
{"Technology": "Python", "Duration": 4}
]
}]
}
Python with Duration 4 has been successfully added to the nested EmployeeProject array.
Conclusion
To $push into a nested array, match the parent array element in the query filter, then use $ (positional operator) + dot notation to target the nested array. For deeper nesting or multiple matches, use $[<identifier>] (arrayFilters) in MongoDB 3.6+.
