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 add a sub-document to sub-document array in MongoDB?
To add a sub-document to a sub-document array in MongoDB, use the $push operator. This operator appends a new document to an existing array field within your MongoDB collection.
Syntax
db.collection.update(
{ "matchField": "value" },
{ "$push": { "arrayField": { newSubDocument } } }
)
Sample Data
Let us first create a collection with documents ?
db.subDocumentToSubDocumentDemo.insertOne(
{
"_id": 101,
"StudentName": "Larry",
"StudentAge": 21,
"StudentDetails": [
{
"StudentCountryName": "US",
"StudentFavouriteSubjectList": [ ]
}
]
}
)
{ "acknowledged": true, "insertedId": 101 }
Following is the query to display all documents from a collection with the help of find() method ?
db.subDocumentToSubDocumentDemo.find().pretty()
{
"_id": 101,
"StudentName": "Larry",
"StudentAge": 21,
"StudentDetails": [
{
"StudentCountryName": "US",
"StudentFavouriteSubjectList": [ ]
}
]
}
Example: Adding Sub-Document to Array
Following is the query to add a sub-document to sub-document array in MongoDB ?
db.subDocumentToSubDocumentDemo.update(
{ "_id": 101 },
{
"$push": {
"StudentDetails": {
"StudentCountryName": "UK",
"StudentFavouriteSubjectList": ["MongoDB", "Java"]
}
}
}
)
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
Let us check all the documents once again ?
db.subDocumentToSubDocumentDemo.find().pretty()
{
"_id": 101,
"StudentName": "Larry",
"StudentAge": 21,
"StudentDetails": [
{
"StudentCountryName": "US",
"StudentFavouriteSubjectList": [ ]
},
{
"StudentCountryName": "UK",
"StudentFavouriteSubjectList": [
"MongoDB",
"Java"
]
}
]
}
Conclusion
The $push operator successfully adds new sub-documents to existing arrays in MongoDB. This operation appends the new document to the end of the specified array field without affecting existing elements.
Advertisements
