James
James

Reputation: 3239

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.

Upvotes: 0

Views: 1054

Answers (2)

lesolorzanov
lesolorzanov

Reputation: 3606

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.

Upvotes: 0

B. Fleming
B. Fleming

Reputation: 7220

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.

Upvotes: 0

Related Questions