My main concern is about in mongodb documentation they use $elemMatch
command for find and pull the element from array, but this is not work when i use.
My document structure is
{
"_id" : ObjectId("55dea445c3ad8cac03a7ed8e"),
"email" : "[email protected]",
"groups" : [
{
"_id" : ObjectId("55dea4a4c3ad8c8005a7ed8f"),
"name" : "All Group"
}
]}
I want to remove groups from document using mongodb query. My Query is :
db.users.update({"_id": ObjectId('55dea445c3ad8cac03a7ed8e')},
{$pull: {"groups": {$elemMatch: {"_id": ObjectId('55dea4a4c3ad8c8005a7ed8f')}}}})
After executing the query, the user document not updated and groups value still there. I am following mongodb documentation as: http://docs.mongodb.org/v2.6/reference/operator/update/pull/
You do not need $elemMatch
with $pull
. It's arguments are basically a "query" on the array itself:
db.users.update(
{"_id": ObjectId('55dea445c3ad8cac03a7ed8e')},
{ "$pull": { "groups": {"_id": ObjectId('55dea4a4c3ad8c8005a7ed8f')}}}
)
So $pull
works much in way an $elemMatch
works within a query, where it's own arguments are treated as a query in the subdocument elements of the array.
It is looking at the individual array elements already, unlike a "query" portion in the document which sees the whole array.
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