Reputation: 139
I want to change single field in all document of my collection. How I can do this in java ? Structure of collection:
"Users"
== SCvm1SHkJqQHQogcsyvrYC9rhgg2 (user)
- "isPlaying" = false (field witch I want to change)
== IOGgfaIF3hjqierH546HeqQHhi30
- "isPlaying" = true
I tried use something like this but it's work
fStore.collection("Users").document().update("isPlaying", false);
I made research and found question about the same problem but that is in JavaScript which I don't understand. Thanks.
Upvotes: 0
Views: 2744
Reputation: 177
You can retrieve all documents in a collection using getDocuments()
and then update each document. The complete code is :
//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);
}
Upvotes: 2
Reputation: 598708
To update a document, you must know the full path for that document. If you don't know the full path, you will need to load each document from the collection to determine that path, and then update it.
Something like:
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());
}
}
});
This code is mostly copy/paste from the documentation, so I recommend spending some more time there.
Upvotes: 1
Reputation:
Firebase experts recommend using transaction https://firebase.google.com/docs/firestore/manage-data/transactions
Upvotes: 1