Is there any way to increment existing value in firestore ?
What I am trying. FirebaseFirestore.getInstance()
.collection("notifications")
.document(response.getString("multicast_id"))
.set(notificationData);
FirebaseFirestore.getInstance()
.collection("users")
.document(post.userId)
.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
int followers = Integer.valueOf(task.getResult().getData().get("followers").toString());
FirebaseFirestore.getInstance()
.collection("users")
.document(post.userId).update("followers", followers++).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
}
});
}
}
});
Database Structure
users
- data....
- followers(number)
According to this Answer function available for increment or decrement numeric field values
Version 5.9.0 - Mar 14, 2019
Added FieldValue.increment(), which can be used in update() and set(..., {merge:true}) to increment or decrement numeric field values safely without transactions.
https://firebase.google.com/support/release-notes/js
Is any function available for incrementing existing value in firestore android?
Firestore Update Entire DocumentgetDatabase() → where we want to update a document. doc() → where we'll be passing references of database, collection and ID of a document that we want to update. setDoc() → where we actually pass new data that we want to replace along with the doc() method.
You can use FieldValue. increment with a double (e.g. FieldValue. increment(1.0) ) or an int (e.g. FieldValue. increment(2) ).
Thanks to the latest Firestore patch (March 13, 2019)
Firestore's FieldValue class now hosts a increment method that atomically updates a numeric document field in the firestore database. You can use this FieldValue sentinel with either set
(with mergeOptions true) or update
methods of the DocumentReference
object.
The usage is as follows (from the official docs, this is all there is):
DocumentReference washingtonRef = db.collection("cities").document("DC");
// Atomically increment the population of the city by 50.
washingtonRef.update("population", FieldValue.increment(50));
If you're wondering, it's available from version 18.2.0
of firestore. For your convenience, the Gradle dependency configuration is implementation 'com.google.firebase:firebase-firestore:18.2.0'
Note: Increment operations are useful for implementing counters, but keep in mind that you can update a single document only once per second. If you need to update your counter above this rate, see the Distributed counters page.
FieldValue.increment()
is purely "server" side (happens in firestore), so you don't need to expose the current value to the client(s).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With