8

I have a document with the following structure:

{
    "email" : "a@gmail.com",
    "value" : 100,
    "children" : [
                  {
                    "email" : "b@gmail.com",
                    "value" : 100
                  },
                  {
                    "email" : "b@gmail.com",
                    "value" : 200
                  }
                 ]
}

I want to remove all elements with the email b@gmail.com from the children array. I am able to remove one item if I pass the whole object to be removed like this:

FieldValue.arrayRemove(childObject)

But I want both the objects with the email b@gmail.com to be removed. Is there anyway to achieve this using FieldValue.arrayRemove()?

Nimish David Mathew
  • 2,958
  • 6
  • 29
  • 45

2 Answers2

8

The arrayRemove operation removes the exact item that you specify from the array. There is no way to pass a partial object and remove all array items that match the partial information. You will have to pass in each complete item that you want to remove.

If you don't know what those items are yet, you will typically have to first read the document, loop over the items in the array to remove them, and write the modified array back to the document.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Is this feature likely to be supported in the future? – Nimish David Mathew Jan 13 '20 at 05:42
  • 1
    Nobody is actively working on adding partial array operations at the moment. If you'd like to cast your vote for them to be added, you can [file a feature request](https://firebase.google.com/support/contact/bugs-features/). But for now, you will have to query-then-remove. – Frank van Puffelen Jan 13 '20 at 16:03
2

As an update, it is still the case that you must match the object exactly to remove it from an array. Additionally, of course, in the example above, he is querying for a value, which requires a query to see what matches.

However, depending on the logic: if you use a Map instead...for instance in the case above, adjusted:

"children" : 
    "b@gmail.com_100":
                      {
                        "email" : "b@gmail.com",
                        "value" : 100
                      },
    "b@gmail.com_200":
                      {
                        "email" : "b@gmail.com",
                        "value" : 200
                      }
             

You can simply use:

'children.b@gmail.com_200': FieldValue.delete(), 

As of late, I've gravitated away from Lists to Maps for this reason.

jbryanh
  • 1,193
  • 7
  • 17