Mongodb $推入嵌套数组

时间:2015-01-10 08:55:40

标签: mongodb mongodb-php

我想在嵌套数组中添加新数据

我的文件是:

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

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

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

以下是我的尝试:

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

2 个答案:

答案 0 :(得分:60)

可能是这样的,ID就是你的ObjectId。第一个{}是识别您的文档所必需的。只要您的集合中有另一个唯一标识符,就不需要使用ObjectId。

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

答案 1 :(得分:1)

这样对我有用!

“播放列表。$ []。音乐”:

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