mongodbunsetfindandmodify

Mongodb findAndUpdate $unset a field with an empty array


This is my example document:

{
  keys: {
    attr1: ['a', 'b', 'c'],
    attr2: ['d', 'e']
  }
}

I remove the items in the array like this...

{
  $pullAll: {
    'keys.attr2': ['d', 'e']
  }
}

And this leaves me with an empty array for the attr2 field:

{
  keys: {
    attr1: ['a', 'b', 'c'],
    attr2: []
  }
}

But what I want to do is if the field is now an empty then I want $unset that field so that the final result looks like this:

{
  keys: {
    attr1: ['a', 'b', 'c']
  }
}

I want to do this within a single find and update operation.

Thanks for the help.


Solution

  • Unfortunately that isn't possible. You can't perform an additional match at the same time that you're performing the update operations. You can, however, perform a second update that matches an empty array and then unsets the field.

    It's just a limitation that you're going to have to work around.