I have a document structure something along the lines of the following:
{
"_id" : "777",
"someKey" : "someValue",
"someArray" : [
{
"name" : "name1",
"someNestedArray" : [
{
"name" : "value"
},
{
"name" : "delete me"
}
]
}
]
}
I want to delete the nested array element with the value "delete me".
I know I can find documents which match this description using nested $elemMatch expressions. What is the query syntax for removing the element in question?
To delete the item in question you’re actually going to use an update. More specifically you’re going to do an update with the
$pullcommand which will remove the item from the array.There’s a little bit of “magic” happening here. Using
.0indicates that we know that we are modifying the 0th item ofsomeArray. Using{"name":"delete me"}indicates that we know the exact data that we plan to remove.This process works just fine if you load the data into a client and then perform the update. This process works less well if you want to do “generic” queries that perform these operations.
I think it’s easiest to simply recognize that updating arrays of sub-documents generally requires that you have the original in memory at some point.
In response to the first comment below, you can probably help your situation by changing the data structure a little
Now you can do
{$pull : { "someObjects.name1.someNestedArray" : ...Here’s the problem with your structure. MongoDB does not have very good support for manipulating “sub-arrays”. Your structure has an array of objects and those objects contain arrays of more objects.
If you have the following structure, you are going to have a difficult time using things like
$pull:If your structure looks like that and you want to update
subarrayyou have two options:$pull.$pull. Load the entire object into a client and usefindAndModify.