简体   繁体   中英

How to update all documents in collection of Firestore?

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.

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);
    }

Firebase experts recommend using transaction https://firebase.google.com/docs/firestore/manage-data/transactions

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM