James
James

Reputation: 6499

How do you remove an embedded document in MongoDB?

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

Answers (3)

Remon van Vliet
Remon van Vliet

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

nnythm
nnythm

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

Sergio Tulentsev
Sergio Tulentsev

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

Related Questions