Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change the value of a field in multiple documents within a collection based on a condition (using Firebase/Flutter)

I have a collection named ‘users’ and within this collection, I simply want to change the value of a field in multiple documents based on a condition. Within the ‘users’ collection there’s a field named ‘username’ which has 400 users with each value being as such:

user1,
user2,
user3,

user400

The goal is to change the value of each field where the username is between user1 and user50. In other words, user1-user50 should have their values changed while user51-user400 should not have any changes. Can this be achieved?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The code below is an example of how to change all values of a field in the users collection but that’s not exactly what I’m trying to achieve. Thank you for any help!

      FirebaseFirestore.instance.collection('users').get().then((snapshot) {
        for (DocumentSnapshot ds in snapshot.docs) {
          ds.reference.update({field: value});
        }
      });

>Solution :

Yes, it can. What you should do is create a separate query for each interval. For example, if you need to update user1-user50, then you should use a query in which you should order the results by the username field and then call Query#startAt(1) and Query#endAt(user50).

There is something that you should also notice. The username field is of type String. This means that when you order strings, the documents that are read are ordered lexicographically. So you might not get the desired results. However, you can simply solve this problem. Instead of storing the user name as a string, you can simply store the number. The username without the user prefix. In this way, you’ll get the correct results using:

FirebaseFirestore.instance.collection('users')
                          .orderBy('username')
                          .startAt(1)
                          .endAt(50)
                          .get()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading