I have a document structure like this:
{
"_id" : "1234",
"name" : "foo",
"bar" : [
{"some0":"value0"},
{"some1":"value1"},
{"some2":"value2"}
]
}
And i just want to delete Objects in the nested "bar" array by its indices within the array eg i have an array of indices like [0,2] which should delete "some0" and "some2" from the array.
I'm aware, that Mongo currently has no way to delete values by its index atomically and usually this is used instead:
db.lists.update({}, {$unset : {"bar.0" : 1 }})
db.lists.update({}, {$pull : {"bar" : null}})
Question: Is there a more efficient way to do this if my array of to be deleted indices gets quite large (>100) than looping over them manually and do the 2 modifications for each of them.
There is no straight way of pulling/removing by array index. In fact, this is an open issue http://jira.mongodb.org/browse/SERVER-1014 , you may vote for it.
Only way is what you have written is correct db.lists.update({}, {$unset : {"bar.0" : 1 }}) db.lists.update({}, {$pull : {"bar" : null}})
You can use positional $
operator identifies an element in an array to update without explicitly specifying the position of the element in the array
db.lists.update({'bar.some0':'value0'}, {$unset : {"bar.$" : 1 }})
some0, some1 you can pass it as dynamic variable
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.