Reputation: 6499
I've got a document that looks like this:
{listName: 'LoremIpsum'
listItems: [{productDescription: "", productImage: ""}...]}
How would I go about deleting an item from listItems if productImage didn't exist?
I've tried the following with no result:
db.lists.update({"item.productImage":{$exists: false}}, {$unset:{"item":1}}, false, true )
Upvotes: 1
Views: 8048
Reputation: 18595
Note that $pull can contain element matching criteria. As such this single update will remove the items that do not contain the field "productImage" :
db.lists.update({}, {$pull:{listItems:{productImage:{$exists:false}}}}, false, true)
Upvotes: 3
Reputation: 3320
You should be able to use the $pull operator, which will remove everything with the matching criterion that you specify.
db.lists.update({}, {"$pull": {"listItems" : {"productImage" : {$exists: false}} }})
Upvotes: 0
Reputation: 230286
It seems that you can't delete it in one step. But here's a two-step combination:
// unset matching array element. That'll leave null on its place
db.lists.update({"listItems.productImage":{$exists: false}},
{$unset:{"listItems.$":1}});
// remove nulls from array
db.lists.update({listItems: null},
{$pull: {listItems: null}});
Upvotes: 0