MongoDB: Adding Data to a Nested Array with $push
In MongoDB, you can store complex data structures, such as nested arrays. When you need to add new elements to these arrays, you can use the $push operator.
Problem:
You want to add a new item to a specific subarray within a document. Your document contains a nested array of music tracks within a playlist. You want to add a new track to an existing playlist.
Example Document:
{ "username": "erkin", "email": "example@email.com", "password": "b", "playlists": [ { "_id": 58, "name": "asdsa", "date": "09-01-15", "musics": [ { "name": "INNA - Cola Song (feat. J Balvin)", "duration": "3.00" } ] } ] }
Desired Result:
{ "username": "erkin", "email": "example@email.com", "password": "b", "playlists": [ { "_id": 58, "name": "asdsa", "date": "09-01-15", "musics": [ { "name": "INNA - Cola Song (feat. J Balvin)", "duration": "3.00" }, { "name": "new", "duration": "3.00" } ] } ] }
Solution:
To add a new item to the musics subarray, you can use the following update query:
db.collection.update( { "_id": ID, "playlists._id": "58"}, { "$push": {"playlists.$.musics": { "name": "test name", "duration": "4.00" } } } )
In this query:
The above is the detailed content of How to Add a New Item to a Nested Array in MongoDB using $push?. For more information, please follow other related articles on the PHP Chinese website!