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!
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.
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.
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.
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'))
)
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With