Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove elements from sub-array mongo document

Tags:

php

mongodb

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!

like image 282
Larry Avatar asked Jul 19 '13 14:07

Larry


People also ask

How do I remove a specific element from an array in MongoDB?

To remove an element, update, and use $pull in MongoDB. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.

How do you remove an element from a doubly nested array in a MongoDB document?

To remove an element from a doubly-nested array in MongoDB document, you can use $pull operator. Now field "UserZipCode": "20010" has been removed from a doubly-nested array.

How do I remove a property from a document in MongoDB?

In MongoDB, you can use the $unset field update operator to completely remove a field from a document. The $unset operator is designed specifically to delete a field and its value from the document.


1 Answers

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'))
    )
);
like image 103
Miguel Cartagena Avatar answered Oct 06 '22 00:10

Miguel Cartagena