0

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.

James
  • 3,051
  • 3
  • 29
  • 41

2 Answers2

0

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.

B. Fleming
  • 7,170
  • 1
  • 18
  • 36
  • Is there a way on a second operation then to `$unset` any fields that have an empty array? I'd say just add it to this answer if you know that solution. Thanks. – James Sep 07 '18 at 23:20
  • 1
    Unfortunately you would need to handle those one at a time, e.g. `db.your_collection.update({'keys.attr1': []}, {$unset: {'keys.attr1': null}}, {multi: true})`. There's not really an elegant "unset all empty fields" operation. – B. Fleming Sep 08 '18 at 00:13
0

What about,

db.collection.updateMany({ field: {$size: 0}} ,{$unset:{field:""}} )

the first doc finds arrays of size 0 and the second unsets it.

Was this what you needed? (just realized this was 4 years ago).

There is also findAndModify() but I see now that it is only for one document.

lesolorzanov
  • 3,536
  • 8
  • 35
  • 53