如何在MongoDB上进行复杂的更新

时间:2014-09-27 19:38:00

标签: mongodb crud mongodb-query

我有一个问题。我的数据是这样的:

{
  "name" : "username",
  "surname" : "surname",
  "playlists": {
    "name": "playlistName",
    "date": "27-09-14",
    "musics": [
      "music name 1",
      "music name 2"
    ]
  },
  "playlists": {
    "name": "playlistName2",
    "date": "27-09-14",
    "musics": [
      "music name 1",
      "music name 2"
    ]
  }

}


我想再添加一个"播放列表"该数据的部分。
我的数据应该是这样的:

{
  "name" : "username",
  "surname" : "surname",
  "playlists": {
    "name": "playlistName",
    "date": "27-09-14",
    "musics": [
      "music name 1",
      "music name 2"
    ]
  },
  "playlists": {
    "name": "playlistName2",
    "date": "27-09-14",
    "musics": [
      "music name 1",
      "music name 2"
    ]
  },
  "playlists" : {
    "blabla" : "blabla"
  }

}

更新查询无效。
我如何能?提前致谢。
我在尝试

  

$ dbData = array(' $ set' =>数组('播放列表' =>数组(' blabla' =>   '布拉布拉')));
      $ users-> update(array(' _id' => new MongoId(' 541f0e2216c8272c058b4567')),                 $ dbData);

1 个答案:

答案 0 :(得分:0)

也可以有多个相同的密钥,但不建议这样做(你有2个playlists密钥,想要更多)。

一个合理的解决方案是将playlists作为数组并将元素推入其中。

{
  "name" : "username",
  "surname" : "surname",
  "playlists": [...]
}

$dbData = array('$push' => array('playlists' => array ('blabla' => 'blabla'))); 
$users->update(array('_id' => new MongoId ('541f0e2216c8272c058b4567')), $dbData);