How to append an array into an array field in firestore?

Question

I have a collection named Users with a field named friendEmails which is an array that contains Strings.

I have a document with friendEmails = {[email protected], [email protected]}, and I want to append newEmails = {[email protected], [email protected]} to it.

Problem

The only options I know for this are:

  1. Reading the friendEmails array first, then adding the union of it and newEmails to the document.

  2. Iterating over the elements of newEmails (let’s and each iteration doing: myCurrentDocumentReference.update(FieldValue.arrayUnion, singleStringElement);
    (Since FieldValue.arrayUnion only lets me pass comma-separated elements, and all I have is an array of elements).

These two options aren’t good since the first requires an unnecessary read operation (unnecessary since FireStore seems to “know” how to append items to arrays), and the second requires many write operations.

The solution I’m looking for

I’d expect Firestore to give me the option to append an entire array, and not just single elements.

Something like this:

ArrayList<String> newEmails = Arrays.asList("[email protected]", "[email protected]");

void appendNewArray() {
    FirebaseFirestore firestore = FirebaseFirestore.getInstance();
    firestore.collection("Users").document("userID").update("friendEmails", FieldValue.arrayUnion(newEmails));
}

Am I missing something? Wouldn’t this be a sensible operation to expect?

How else could I go about performing this action, without all the unnecessary read/write operations?

Thanks!

Answer

You can add multiple items to an array field like this using FieldValue.arrayUnion() as the value of a field update:

docRef.update("friendEmails", FieldValue.arrayUnion(email1, email2));

If you need to convert an ArrayList to an array for use with varargs arguments:

docRef.update("friendEmails", FieldValue.arrayUnion(
    newEmails.toArray(new String[newEmails.size()])
));