If you really want to unset
it first and then pull the element(s) missing key
off the array use:
db.test.update(
{ "_id": 1 }, // you can also use { } to clean up the whole collection
{ $pull: { "list": { "key": {$exists: false} } } }
)
But if there is not strong reason for this use pull
to do it in one shot:
db.test.insert({
"_id" : 1,
"list" : [ { "key": "a" }, { "key": "b" }, { "key": "c" } ]
})
You can use pull to remove from the document where list
contains a key
with value b
:
db.test.update({
"list.key": "b" },
{ $pull: { "list": {"key": "b" } }
})
This removes the respective element from the array:
db.test.find()
{ "_id" : 1, "list" : [ { "key" : "a" }, { "key" : "c" } ] }