Home >Backend Development >PHP Tutorial >How to Add Data to Nested Arrays in MongoDB using $push?
Problem:
In MongoDB, you have a document with a nested array (e.g., "musics" inside "playlists"). You want to insert a new element into the nested array.
Solution:
To add data to a nested array using the $push operator, you can follow these steps:
Within the "$push" operator, define the new element to be inserted as an object with property-value pairs (e.g., "name" and "duration" for the music object).
Example:
db.collection.update( { "_id": ObjectId("584654654ad21"), "playlists._id": 58 }, { "$push": { "playlists.$.musics": { "name": "new name", "duration": "3.00" } } } );
This query will update the document with an _id of "584654654ad21" and a playlist with an _id of 58 by adding a new music object with the specified name and duration to the "musics" array.
Note: The "$push" operator can only be used to add elements to arrays. It cannot be used to modify existing elements or add elements to arrays that do not exist.
By following these steps, you can effectively add data to nested arrays in MongoDB documents.
The above is the detailed content of How to Add Data to Nested Arrays in MongoDB using $push?. For more information, please follow other related articles on the PHP Chinese website!