[英]How to update all documents in collection of Firestore?
我想更改我收藏的所有文档中的单个字段。 我如何在 java 中做到这一点? 收藏结构:
"Users"
== SCvm1SHkJqQHQogcsyvrYC9rhgg2 (user)
- "isPlaying" = false (field witch I want to change)
== IOGgfaIF3hjqierH546HeqQHhi30
- "isPlaying" = true
我尝试使用这样的东西,但它的工作
fStore.collection("Users").document().update("isPlaying", false);
我进行了研究,发现了关于同样问题的问题,但那是在 JavaScript 中,我不明白。 谢谢。
您可以使用getDocuments()
检索集合中的所有文档,然后更新每个文档。 完整的代码是:
//asynchronously retrieve all documents
ApiFuture<QuerySnapshot> future = fStore.collection("Users").get();
List<QueryDocumentSnapshot> documents = future.get().getDocuments();
for (QueryDocumentSnapshot document : documents) {
document.getReference().update("isPlaying", true);
}
Firebase 专家推荐使用事务https://firebase.google.com/docs/firestore/manage-data/transactions
要更新文档,您必须知道该文档的完整路径。 如果您不知道完整路径,则需要从集合中加载每个文档以确定该路径,然后对其进行更新。
就像是:
db.collection("Users")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
document.getReference().update("isPlaying", false);
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
这段代码主要是从文档中复制/粘贴的,所以我建议花更多时间在那里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.