Reputation: 4566
I've seen this question before for an earlier version of Firebase that is no longer applicable for Firebase Cloud Firestore.
I would like to make a query that checks a document's field's value against a list of potential values, something like whereEqualTo(someField, a OR b OR c OR ... OR n)
. Specifically, I have a list of potential values for a single field of type Reference and I want my query to return all documents in the specified collection whose value of the field is equal to one of the potential values in the list. I am also using .limit(10)
because I am paginating data.
So for example, if my list contained the References [ref1, ref2, ref3] then the query would be similar to joining these 3 queries:
Query query1 = mDatabase.collection("myCollection").whereEqualTo("refField", ref1);
Query query2 = mDatabase.collection("myCollection").whereEqualTo("refField", ref2);
Query query3 = mDatabase.collection("myCollection").whereEqualTo("refField", ref3);
On the documentation, under the "Limitations" section, it mentions:
Logical OR queries. In this case, you should create a separate query for each OR condition and merge the query results in your app.
So maybe the best way would be to merge query results, but how could this be done, and with limiting to 10 results?
Note that I am working with Java for Android Development.
Upvotes: 2
Views: 1802
Reputation: 139039
I would like to make a query that checks a document's field's value against a list of potential values.
Unfortunately, there is no query in Firestore that can help you achieve this. What can you do instead is to get all the documents beneath your myCollection
collection and check the value of document field you need against a list of potential values like this:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference myCollectionRef = rootRef.collection("myCollection");
myCollectionRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<String> yourList = new ArrayList<>();
for (QueryDocumentSnapshot document : task.getResult()) {
DocumentReference reference = document.getDocumentReference("refField");
String stringReference = reference.getPath();
if (yourList.contains(stringReference)) {
Log.d(TAG, "Reference found!");
}
}
}
}
});
I assumed your list contains document references of type String. As you can see, we need to serialize a DocumentReference
objects that we get from the database by using getPath()
method to get a String that describes the document's location in the database. To deserialize that path String back into a DocumentReference
object, use FirebaseFirestore.getInstance().document(path) method.
PS. If you are interested about pagination, this is how you can paginate queries by combining query cursors with the limit() method. I also recommend you take a look at this video for a better understanding.
Upvotes: 2