Mongodb $push in nested array

balkondemiri picture balkondemiri · Jan 10, 2015 · Viewed 50.2k times · Source

I want add new data my nested array

My document is:

{
  "username": "erkin",
  "email": "[email protected]",
  "password": "b",
  "playlists": [
    {
      "_id": 58,
      "name": "asdsa",
      "date": "09-01-15",
      "musics": [
        {
          "name": "INNA - Cola Song (feat. J Balvin)",
          "duration": "3.00"
        },
        {
          "name": "blabla",
          "duration": "3.00"
        }
      ]
    }
  ]
}

I want add music in this playlist section:

{
  "username": "erkin",
  "email": "[email protected]",
  "password": "b",
  "playlists": [
    {
      "_id": 58,
      "name": "asdsa",
      "date": "09-01-15",
      "musics": [
        {
          "name": "INNA - Cola Song (feat. J Balvin)",
          "duration": "3.00"
        },
        {
          "name": "blabla",
          "duration": "3.00"
        },
        {
          "name": "new",
          "duration": "3.00"
        }
      ]
    }
  ]
}

Here is what I tried:

$users->update(
  array(
    '_id' => new MongoId (Session::get('id')),
    'playlists._id' => $playlistId
  ),
  array(
    '$push' => array('playlists.musics' => array(
      'name' => 'newrecord',
      'duration' => '3.00'
    ))
  )
);

Answer

Thomas Bormans picture Thomas Bormans · Jan 10, 2015

Probably something like this where ID is your ObjectId. The first {} are necessary to identify your document. It is not required to use an ObjectId as long as you have another unique identifier in your collection.

db.collection.update(
    { "_id": ID, "playlists._id": "58"},
    { "$push": 
        {"playlists.$.musics": 
            {
                "name": "test name",
                "duration": "4.00"
            }
        }
    }
)