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?
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()