So I have a set of items in Firestore, and I want to change a property in a document when a criteria is met in Firestore.

  • Rooms collection
    • Room document
      • all_answered property
    • Users collection
      • guid User doc
        • answered property
      • guid User doc
        • answered property

When every user in the users collection has the answered property as true, I want to set the "all_answered" property to true as well in the Room document. These User docs will be on different devices, obviously. How can I do this?

Solution 1: Frank van Puffelen

There are a few common approaches here, and some complications. For easier parsing I'll put them in a list.

  • "All answered" is a dynamic value, i.e. when a new user joins the system the value should become false again. For this reason I recommend keeping a counter for the number of users that have answered, and for the total number of users. If the two values are the same, all people have answered.

  • With that, you can then update the answeredCount property whenever any user updates their answered property value. Doing this in a transaction or batched write to ensure it's atomic.

  • Then when you need to know if all users have answered, you read the user count in your code, and then run a query where you compare answeredCount with the value you just read.

An alternative approach, closer to what you suggest already in your question:

  • You could also periodically run a query that counts the number of users and the number of users that answered (both with the new COUNT() feature), and sets the flag field based on these counts).