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);
}
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.
Firebase experts recommend using transaction https://firebase.google.com/docs/firestore/manage-data/transactions
Related
I'm trying to get all of the document ids in a collection groups. The document id is the group name which is unique. Also each document in groups does not have fields, only pointers to other collections. I wrote the following code:
fireDB.collection("groups").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
QuerySnapshot querySnapshots = task.getResult();
if (querySnapshots != null) {
for (QueryDocumentSnapshot currentDocumentSnapshot : querySnapshots) {
groups.add(currentDocumentSnapshot.getId());
}
Collections.sort(groups);
ArrayAdapter<String> adapter = new ArrayAdapter<>(SignUpActivity.this,android.R.layout.simple_list_item_1,groups);
groupNameText.setAdapter(adapter);
} else {
Log.d(this.getClass().getName(), "No groups in the database");
}
} else {
Log.d(this.getClass().getName(), "addOnCompleteListener:failed");
}
}
});
But groups is always empty because firebase does not give me documents without fields (figured it out after some debugging). How should I do it?
I sounds like you have some subcollections under document paths, without having a document at that path. This is a valid situation, but I don't think it is possible to get those locations in the client-side SDKs, as there is no document there.
See https://www.reddit.com/r/Firebase/comments/b0poug/empty_virtual_docs_this_document_does_not_exist/
The Firebase console shows these locations in italics, since it needs to show the subcollections under each location. It likely uses the show_missing flag in the REST API or Admin SDK for that.
how to get id for document a ?
const name=prod['categ'].value;
const a=db.collection('Categories').whereEqualTo("Name", name);
b=a.id;
You're not yet executing the query, which is necessary to get its ID.
Something like:
const query = db.collection('Categories').whereEqualTo("Name", name);
query.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());
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
The majority of that code is copied straight from the Firebase documentation on getting multiple documents from a collection, so I recommend spending some time studying that.
I have a collection called 'Quiz' and its document contains Quiz category. How do I get all the category documents? Like only(Science,Technology..etc..)
View Image
I have tried with this code:
db.collection("Quiz")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d("KKKK : ", document.getId() + " => " + document.getData());
}
} else {
Log.d("KKKK : ", "Error getting documents: ", task.getException());
}
}
});
But it never returns a value I have changed Firebase rule to allow read, write: if true;
If db object is defined as follows:
FirebaseFirestore db = FirebaseFirestore.getInstance();
To get all documents that exist within Questions subcollection, please use the following reference:
db.collection("Quiz").document("Science")
.collection("Questions")
.get()
.addOnCompleteListener(/* ... */);
See, you need to add all collection and document names in your reference, not only one, as it is in your actual code right now.
I would like to get documents in a sub-collection where the date=DATE and title=TITLE in a document. I'm using date and title as primary keys so that I can display information from the documents from sub-collection "bulletin". How would I do that in Android Studio?
Or would it be better to use a different structure?
Thanks!
Image - Firestore Structure
To solve this, please use the following lines of code:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference bulletinRef = rootRef.collection("bulletin");
bulletinRef.whereEqualTo("date", date).whereEqualTo("title", title).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.getString("title"));
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
The result in your logcat will be, all titles from all documents within your bulletin collection.
I am trying to access a field labeled vote_count via Cloud Firestore realtime updates.
Below is my data structure:
Previously, under Firebase Realtime Database, I would .addValueEventListener() and drill down to the "answer." However, with Cloud Firestore, it is a bit more complex.
mStoreSelectedPollRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(final DocumentSnapshot documentSnapshot, FirebaseFirestoreException e) {
if (e != null){
Log.v("LISTEN", "LISTEN_FAILED");
return;
}
if (documentSnapshot != null){
Log.v("Current Data", String.valueOf(documentSnapshot.getData()));
mStoreSelectedPollRef.collection(ANSWERS_LABEL).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
updatePollResultAnswersDynamically(task.getResult().size(), documentSnapshot);
}
});
} else {
Log.v("Current Data", "Current Data Nulll");
}
}
});
Right now, I am adding a call to .get() within my Snapshot Listener, which seems to be inefficient. I was curious how I would access the:
Total number of answer Documents.
Each individual answer
Given this snippet:
mStoreSelectedPollRef.collection(ANSWERS_LABEL).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
updatePollResultAnswersDynamically(task.getResult().size(), documentSnapshot);
}
});
You can get the total number of answer documents with:
task.getResult().size()
Since you already have this code, I'm not really sure what you're asking. If you're asking if there is a way to get the count without getting the documents, look here: https://stackoverflow.com/a/46555026
To access the individual answer documents, you loop over the query snapshot:
for (DocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
}