Flutter Firestore how to add document with data to all users where a certain collection in my users collection has a document ID of a certain value

Issue

I would like to know how to add document with data to all users where a certain collection in my users collection has a document ID with a certain value . This image would describe best on how structure looks and to explain question more clearly . my users collection

So what I have been able to do is to get all my user ids and add it in to an array -> userIDs .

await FirebaseFirestore.instance
            .collection("users")
            .get()
            .then((snapshots) { 

          final userIDs  [];

          if (snapshots.docs.isEmpty) {
            print('nothing found');
          } else {
            for (var i  0;
                i < snapshots.docs.length;
                i++) {
              userIDs.add(snapshots.docs[i].id);
            }
          }

From there I know I am supposed to perform a WHERE query and add the new document(data) for each userID where the query was true . As I am still fairly new with Firestore CRUD operations , I do not know on how to this . Some help or guidance would be greatly appreciated . Thanks

UPDATED : I added the code as per https://stackoverflow.com/users/5519300/tarik-huber reply into a Streambuilder , but it doesnt seem to retrieve any data . Any idea what issue could be ? Thanks

Container(
              height: 500,
              child: StreamBuilder<QuerySnapshot>(
                stream: FirebaseFirestore.instance
                    .collectionGroup('user_selected_schools')
                    .where(FieldPath.documentId, isEqualTo: "Liebenberg Primary School")
                    .snapshots(),
                builder: (context, snapshot) {
                  if (!snapshot.hasData) {
                    return Center(
                      child: LinearProgressIndicator(),
                    );
                  } else
                    return ListView(
                      children: snapshot.data!.docs.map((doc) {
                        return Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: ListTile(
                            title: Text(
                              doc.id,
                            ),
                            //subtitle: Text(doc['content']),
                          ),
                        );
                      }).toList(),
                    );
                },
              ),
            ),

UPDATE

FirebaseFirestore.instance
.collection('users')
.where('selected_schools', arrayContainsAny: ['School Name 1', 'School 
Name 2'])
.get()

This was the simpler solution I used from answer. I am able to get uid based on selected school from Array . Thank you so much for your help !!!

Solution

I would strongly recommend not to getAll users and filter later on them. If your app grows in size it would cause you a much higher bill than expected.

Instead try to use a collectionGroup query in firestore to get only those users you want to change. The Flutter SKD also supports them.

In a combination with the FieldPath.documentId for the document ID as it is he school name you can query directly trough all Users to get only those you want.

Your query could look like this:

FirebaseFirestore.instance
  .collectionGroup('user_selected_schools')
  .where(FieldPath.documentId, isEqualTo: "School Name")
  .get()

Alternatibely you could also save the school names into an array like selected schools and query with an arrayContains query. This ways you could even search for multiple schools selected at once.

This is how that solution would look like:

FirebaseFirestore.instance
  .collection('users')
  .where('selected_schools', arrayContainsAny: ['School Name 1', 'School Name 2'])
  .get()

Answered By – Tarik Huber

Leave a Comment