Working with Firestore Arrays

Have you ever wanted to make a query to Firestore for all documents with an array containing a certain value? Array queries are possible as of Firebase JS SDK v5.3.0. In addition, the SDK also added support for the atomic addition and removal of elements on an array field.

Firestore Arrays

Queries

Firebase introduced an array-contains operator that can be used with where to query array fields. It will return all documents that contain a the provided value in the array. Currently, this is only supported with one value, so don’t try chaining more than one of these in a single query.

const col = firestore.collection('carts');

const query = col.where('items', 'array-contains', 'fruit loops')

query.get(...)

Use array-contains-any to query a list of many possible matches.

const query = col.where('items', 'array-contains-any', ['fruit loops', 'corn-pops', 'wheaties'])

Writes

How to delete a specific item from an array? Use arrayRemove

import * as firebase from 'firebase/app';

const const arrayRemove = firebase.firestore.FieldValue.arrayRemove;

const doc = firestore.doc('carts/abc');

doc.update({
    items: arrayRemove('chex')
});

How to add new items to an array?

const const arrayUnion = firebase.firestore.FieldValue.arrayUnion;

doc.update({
    items: arrayUnion('coco puffs')
});

Questions? Let's chat

Open Discord