2013-07-19 94 views
3

我試圖從mongo文檔中刪除子數組元素。我的文檔(記錄)是這樣的:從子數組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 
) 

但玩家仍文檔中存在。

謝謝!

回答

6

你更新的對象應該是這樣的:

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

所以在PHP這將是:

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

感謝的人!有用! – Larry