从子数组mongo文档中删除元素

时间:2013-07-19 14:24:35

标签: php mongodb

我正在尝试从mongo文档中删除子数组元素。我的文件(记录)是这样的:

{
    "_id" : 1,
    ...,
    "team" : {
        "players" : [{
            "name" : "A B",
            "birthday" : new Date("11/11/1995")
          }, {
            "name" : "A C",
            "birthday" : new Date("4/4/1991")
          }],
        "matches" : [{
            "against" : "Team B",
            "matchDay" : new Date("11/16/2012 10:00:00")
          }]
      }
}

现在我要从文档中删除“A B”播放器。我试过这个:

$result = $collection->update(
    array('_id' => 1), 
    array('$pull' => array('team.players.name' => 'A B'))
);

结果似乎没问题

(
    [updatedExisting] => 1
    [n] => 1
    [connectionId] => 8
    [err] => 
    [ok] => 1
)

但播放器仍然存在于文档中。

谢谢!

1 个答案:

答案 0 :(得分:7)

您的更新对象应该是这样的:

{
    "$pull": {
        "team.players": {
            name: "A C"
        }
    }
}

所以在php中它将是:

$result = $collection->update(
    array('_id' => 1), 
    array('$pull' => 
        array('team.players' => array('name' = > 'A B'))
    )
);
相关问题