Home >Backend Development >PHP Tutorial >How to Add Data to Nested Arrays in MongoDB using $push?

How to Add Data to Nested Arrays in MongoDB using $push?

Linda Hamilton
Linda HamiltonOriginal
2024-12-26 05:52:42838browse

How to Add Data to Nested Arrays in MongoDB using $push?

MongoDB: Adding Data to Nested Arrays 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:

  • Use the "$push" operator within an update statement.
  • Identify the document to be updated using an appropriate query (e.g., "_id" field).
  • Specify the nested array using dot notation (e.g., "playlists.musics").
  • 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn