I want to create a query for Google Cloud Firestore based on multiple conditions. Here's the code I have so far:
FirebaseFirestore db = FirebaseFirestore.getInstance();
Query someQuery = db.collection("someCollection");
if (someBoolean) {
someQuery = someQuery.whereEqualTo("SomeField", "SomeValue");
}
if (someBoolean2) {
someQuery = someQuery.whereEqualTo("SomeField2", "SomeValue2");
}
// Add limit to the query
someQuery = someQuery.limit(1);
// Execute the query
someQuery.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
if (task.getResult().isEmpty()) {
Log.d("LOG", "NO DOCUMENTS FOUND");
} else {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d("LOG", document.getId() + " => " + document.getData());
}
}
} else {
Log.d("TAG", "---ERROR---");
}
}
});
The issue is that this code seems to return all documents in the collection, rather than applying the conditions (whereEqualTo).
Can anyone help me identify what I'm doing wrong or suggest the correct way to structure this query?
In numerous places, you do this:
if (someBoolean){
someQuery.whereEqualTo("SomeField", "SomeValue");
}
This RETURNS a new Query with the .where() condition added - it DOES NOT modify the original query. someQuery
is exactly the same after. You need to save the returned value, for example:
if (someBoolean){
someQuery = someQuery.whereEqualTo("SomeField", "SomeValue");
}