2015-01-10 66 views
27

我要添加新的數據我嵌套數組

我的文檔是:

{ 
    "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" 
     } 
     ] 
    } 
    ] 
} 

我想添加的音樂在此播放列表部分:

{ 
    "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" 
     } 
     ] 
    } 
    ] 
} 

這裏我試過的:

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

只是爲了填補你在這裏downvote或投票結束的原因。在您的問題中發佈相關的代碼部分。不要在外部鏈接(可能會中斷),也不要讓我們閱讀儘管長列表只是爲了弄清楚你在說什麼。閱讀此:http://stackoverflow.com/help/mcve –

回答

43

可能是這樣的,其中ID是你的ObjectId。第一個{}是識別您的文檔所必需的。只要您的集合中有另一個唯一標識符,則不需要使用ObjectId。

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

嗨。您不指定播放列表_id。我有多個播放列表每個用戶 – balkondemiri

+0

嗯,錯過了。我已經更新了我的答案。 –

+0

我正在嘗試。這個代碼不工作:( – balkondemiri