Firebase Firestore - OR query

Firestore now supports "IN" queries for this purpose.

The query would look like this:

database.collection("collectionName").where("fieldName", "in", ["fieldValue1", "fieldValue2"]);

You can have up to 10 values (fieldValueX) to check "IN" of.


The code OP desired would be as follows:

database.collection("posts").where("blogId", "in", ["1", "2"]); 

You could combine the Observables and return as one

orQuery(){

    const $one = this.afs.collection("posts", ref => ref.where("blogId","==","1")).valueChanges();
    const $two = this.afs.collection("posts", ref => ref.where("blogId","==","2")).valueChanges();

    return combineLatest($one,$two).pipe(
        map(([one, two]) => [...one, ...two])
    )
}

getOr(){
    this.orQuery().subscribe(data => console.log(data))
}

Firebase has listened to our requests and they have included IN query from 7 Nov, 2019. It's a kind of OR query, where you can have upto 10 OR filters.

For android:

collection("posts").whereIn("blogId", Arrays.asList("1", "2"))
.orderBy("timestamp", Query.Direction.DESCENDING).limit(50);

Firebase documentation


I couldn't find any documentation for the ability to OR together where conditions. But you can rephrase your requirement on the blogId as follows:

WHERE blogId > 0 AND blogId < 3

Try this code:

collection("posts")
.where("blogId", ">", "0")
.where("blogId", "<", "3")
.orderBy("timestamp", Query.Direction.DESCENDING)
.limit(50)

OR operator is not accepted in firebase firestore:

Cloud Firestore provides limited support for logical OR queries. The in, and array-contains-any operators support a logical OR of up to 10 equality (==) or array-contains conditions on a single field. For other cases, create a separate query for each OR condition and merge the query results in your app.

Queries in Cloud Firestore, Query limitations

Normally using firebase syntax you can call two collections:

const res1 = async collection("posts", ref => ref.where('blogId', '==', 1).get();
const res2 = async collection("posts", ref => ref.where('blogId', '==', 2).get();

and you can merge the results before serving to the view.

But in this case where you have blogIds you can use this syntax: collection("posts").orderBy('blogId').startAt(1).endAt(2);

e.d