Larry
Larry

Reputation: 461

remove elements from sub-array mongo document

I`m trying to remove a subarray element from a mongo document. My document(record) is something like this:

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

Now I want to remove "A B" player from my document. I tried this:

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

The result seems to be OK

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

but the player still exists in the document.

Thanks!

Upvotes: 5

Views: 3124

Answers (1)

Miguel Cartagena
Miguel Cartagena

Reputation: 2606

Your update object should be like that:

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

So in php it will be:

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

Upvotes: 8

Related Questions