Can Firestore update multiple documents matching a condition, using one query?

firestore batch update
firestore update document field
firestore search query
firestore or query
firestore query nested object
firestore join query
angular firestore transaction
get all documents in collection firestore

In other words, I'm trying to figure out what is the Firestore equivalent to this in SQL:

UPDATE table SET field = 'foo' WHERE <condition>`

Yes, I am asking how to update multiple documents, at once, but unlike the linked questions, I'm specifically asking how to do this in one shot, without reading anything into memory, because there's no need to do so when all you want is to set a flag on all documents matching a condition.

db.collection('table')
  .where(...condition...)
  .update({
    field: 'foo',
  });

is what I expected to work, CollectionReference doesn't have an .update method.

The Transactions and Batched Writes documentation mentions transactions and batched writes. Transactions are out because "A transaction consists of any number of get() operations followed by any number of write operations" Batched writes are also not a solution because they work document-by-document.

With MongoDB, this would be

db.table.update(
  { /* where clause */ },
  { $set: { field: 'foo' } }
)

So, can Firestore update multiple documents with one query, the way SQL database or MongoDB work, i.e. without requiring a round-trip to the client for each document? If not, how can this be done efficiently?

Updating a document in Cloud Firestore requires knowings its ID. Cloud Firestore does not support the equivalent of SQL's update queries.

You will always have to do this in two steps:

  1. Run a query with your conditions to determine the document IDs
  2. Update the documents with individual updates, or with one or more batched writes.

Note that you only need the document ID from step 1. So you could run a query that only returns the IDs. This is not possible in the client-side SDKs, but can be done through the REST API and Admin SDKs as shown here: How to get a list of document IDs in a collection Cloud Firestore?

Can Firestore update multiple documents matching a condition , Cloud Firestore provides powerful query functionality for specifying which documents you want to retrieve from a These queries can also be used with either get() or addSnapshotListener() , as described in Get Data and Get Realtime Updates. Note: While the code samples cover multiple languages, the text explaining the  Get multiple documents from a collection. You can also retrieve multiple documents with one request by querying documents in a collection. For example, you can use where() to query for all of the documents that meet a certain condition, then use get() to retrieve the results:

Frank's answer is actually a great one and does solve the issue.

But for those in a hurry maybe this snippet might help you:

const updateAllFromCollection = async (collectionName) => {
    const firebase = require('firebase-admin')

    const collection = firebase.firestore().collection(collectionName)

    const newDocumentBody = {
        message: 'hello world'
    }

    collection.where('message', '==', 'goodbye world').get().then(response => {
        let batch = firebase.firestore().batch()
        response.docs.forEach((doc) => {
            const docRef = firebase.firestore().collection(collectionName).doc(doc.id)
            batch.update(docRef, newDocumentBody)
        })
        batch.commit().then(() => {
            console.log(`updated all documents inside ${collectionName}`)
        })
    })
}

Just change what's inside the where function that queries the data and the newDocumentBody which is what's getting changed on every document.

Also don't forget to call the function with the collection's name.

Transactions and batched writes, We will be able to query multiple documents and tell users the top X Firestore does not support incrementing values (i.e., count+=1). Tip: For simplicity, we did not use a transaction when updating the data count. The type is added to help queries find documents that match the request being made,  I've been using Firestore in many projects for a year now. I wanted to share a React hooks library I made to let you query Firestore in React with basically zero boilerplate. It's called swr-firestore. It's built on top of the awesome swr library by Vercel, which means you get tons of cool benefits, like caching, shared data across components, etc.

If anyone's looking for a Java solution:

public boolean bulkUpdate() {
  try {
    // see https://firebase.google.com/docs/firestore/quotas#writes_and_transactions
    int writeBatchLimit = 500;
    int totalUpdates = 0;

    while (totalUpdates % writeBatchLimit == 0) {
      WriteBatch writeBatch = this.firestoreDB.batch();

      List<QueryDocumentSnapshot> documentsInBatch =
          this.firestoreDB.collection("animals")
              .whereEqualTo("species", "cat")
              .limit(writeBatchLimit)
              .get()
              .get()
              .getDocuments();

      if (documentsInBatch.isEmpty()) {
        break;
      }

      documentsInBatch.forEach(
          document -> writeBatch.update(document.getReference(), "hasTail", true));

      writeBatch.commit().get();

      totalUpdates += documentsInBatch.size();
    }

    System.out.println("Number of updates: " + totalUpdates);

  } catch (Exception e) {
    return false;
  }
  return true;
}

Perform simple and compound queries in Cloud Firestore, Transactions and batched writes, Can Firestore update multiple documents matching a condition, using one query​? Transactions are out because "A  This query returns every city document where the regions field is an array that contains west_coast. Beginnings of a Firestore CRUD Library for PHP. In this case, you should create a separate query for each OR condition and merge the query results in your app. Documents can be in more than one Room.

Update and Customize Queries on Your Cloud Firestore Data for , You can also use update method of DocumentReference to update fields of the base on id, "upsert: true" option use to check if there is no matching _id it will React. Is it possible to store multiple documents in Firestore with only one request? You will always have to do this in two steps: Run a query with your conditions  But Firestore rules can also be used in a more granular fashion to limit writes on individual fields within documents rather than the whole documents themselves. We can use this to allow users to update only the ratings, average rating, and the number of ratings for a restaurant, removing the possibility of a malicious user altering a

Firestore transaction update multiple documents in a single transaction, Understanding how queries work on the Firestore Database is one of the valuable skills Get Data from Sub-collection; Firestore Single/Multiple Where Query Filter; OrderBy and You can delete an entire document from Cloud Firestore using delete() method by These arguments look very similar to an if condition block. yarn add @nandorojo/swr-firestore # or npm install @nandorojo/swr-firestore Install firebase: # if you're using expo: expo install firebase # if you aren't using expo: yarn add firebase # or npm i firebase Set up. In the root of your app, create an instance of Fuego and pass it to the FuegoProvider.

Firestore update multiple documents, With the in query, you can query a specific field for multiple values and Cloud Firestore will match any document whose field equals one of  The SF document, however, does not match because its region field is ["west_coast", "norcal"]. Limitations. Note the following limitations for in and array-contains-any: in and array-contains-any support up to 10 comparison values. You can use only one in or array-contains-any clause per query. You can't use both in and array-contains-any in

Comments
  • You could reuse your collection variable in the initialization of docRef, right? const docRef = collection.doc(doc.id)