Ashvin solanki
Ashvin solanki

Reputation: 4809

Increment existing value in firebase firestore

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?

Upvotes: 9

Views: 10697

Answers (1)

Ashvin solanki
Ashvin solanki

Reputation: 4809

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).

Upvotes: 22

Related Questions