Mongodb $push in nested array

不问归期 提交于 2019-11-25 22:47:37

问题


I want add new data my nested array

My document is:

{
  \"username\": \"erkin\",
  \"email\": \"erkin-07@hotmail.com\",
  \"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\": \"erkin-07@hotmail.com\",
  \"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\'
    ))
  )
);

回答1:


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"
            }
        }
    }
)



回答2:


This way it worked for me!

"playlists.$[].musics":

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

https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/#position-nested-arrays-filtered



来源:https://stackoverflow.com/questions/27874469/mongodb-push-in-nested-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!