2015-01-10 46 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