增加 firebase firestore 中的现有值

Ash*_*nki 8 java android firebase google-cloud-firestore

有没有办法增加firestore 中的现有值?

我正在尝试什么。
    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) {
                    }
                });
            }
        }
    });
Run Code Online (Sandbox Code Playgroud) 数据库结构
users

  - data....
  - followers(number)
Run Code Online (Sandbox Code Playgroud)

根据此答案函数可用于增加或减少数字字段值

版本 5.9.0 - 2019 年 3 月 14 日

添加了 FieldValue.increment(),它可以在 update() 和 set(..., {merge:true}) 中使用,以在没有事务的情况下安全地递增或递减数字字段值。

https://firebase.google.com/support/release-notes/js

是否有任何函数可用于增加 firestore android 中的现有值?

Ash*_*nki 17

感谢最新的 Firestore 补丁(2019 年 3 月 13 日)

Firestore 的 FieldValue 类现在托管一个增量方法,该方法自动更新Firestore数据库中的数字文档字段。您可以将此 FieldValue 标记与对象的set(使用 mergeOptions true)或update方法一起使用DocumentReference

用法如下(来自官方文档,仅此而已):

DocumentReference washingtonRef = db.collection("cities").document("DC");

// Atomically increment the population of the city by 50.
washingtonRef.update("population", FieldValue.increment(50));
Run Code Online (Sandbox Code Playgroud)

如果您想知道,它可以从18.2.0firestore 的版本中获得。为了您的方便,Gradle 依赖配置是implementation 'com.google.firebase:firebase-firestore:18.2.0'

注意:增量操作对于实现计数器很有用,但请记住,您每秒只能更新单个文档一次。如果您需要将计数器更新到高于此速率,请参阅 分布式计数器页面。


FieldValue.increment() 纯粹是“服务器”端(发生在 Firestore 中),因此您不需要将当前值公开给客户端。