5

我正在尝试从 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
)

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

谢谢!

4

1 回答 1

8

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

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

所以在php中它将是:

$result = $collection->update(
    array('_id' => 1), 
    array('$pull' => 
        array('team.players' => array('name' = > 'A B'))
    )
);
于 2013-07-19T14:46:27.397 回答