Home > Backend Development > PHP Tutorial > How to Add a New Item to a Nested Array in MongoDB using $push?

How to Add a New Item to a Nested Array in MongoDB using $push?

Mary-Kate Olsen
Release: 2024-12-14 05:14:16
Original
255 people have browsed it

How to Add a New Item to a Nested Array in MongoDB using $push?

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"
        }
      ]
    }
  ]
}
Copy after login

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"
        }
      ]
    }
  ]
}
Copy after login

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"
            }
        }
    }
)
Copy after login

In this query:

  • "_id": ID identifies the document you want to update.
  • "playlists._id": "58" specifies the specific playlist within the document where you want to add the new item.
  • "$push" performs the update operation.
  • {"playlists.$.musics": ...} pushes the new item into the musics subarray.

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template