Mongodb update() with $unset/$pull not doing $pull

Problem

I am trying to remove some items from an array in a document in MongoDB:

doc1
  items
    item
       id=1
    item
       id=2
    item
       id=3
doc2
  items
    item
      id=4
    item
      id=5
    item
      id=6

I use this to remove for example item id=5:

(...)
updateItems({'items.id': 5},    { $unset: { 'items.$': 1 }},    { $pull: {'items'    : null} });
(...)
function updateItems(objmatch, objunset, objpull){  
coremodels.getProfileTable(req).update(
    objmatch, 
    objunset,
    {multi: true}, function(err) {
        coremodels.getProfileTable(req).update(
                        objmatch, 
                        objpull,
                        {multi: true}, function(err) {
        console.log('COMPLETED');
});
(...)                       

The $unset works fine, but the $pull doesn't seem to be working. The end result of this operation is an empty (Null) item 5.

Any ideas why the $pull is not removing the empty document?

Many thanks in advance.

Problem courtesy of: Rafa Llorente

Solution

Your updateArray function takes two parameters, but you're passing it three. I don't think you're sending { $pull: {'items' : null} } to the driver at all.

Added:

Once you nullify item 5, your match document no longer matches anything . The second time you cal update, try replacing objmatch with { }, which should just remove any nulls.

Solution courtesy of: paulmelnikow

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.