Firebase Firestore - OR query

2020-01-24 09:29发布

How to get data by multiple values of one field? For example, I have database with posts and I want to query for all posts where blogId is 1 or 2, sorting by timestamp.

collection("posts").whereEqualTo("blogId", "1")
.whereEqualTo("blogId", 2).orderBy("timestamp", Query.Direction.DESCENDING).limit(50)

Code above is not working :(

How to achieve this? Regards :)

8条回答
做自己的国王
2楼-- · 2020-01-24 09:50

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

查看更多
走好不送
3楼-- · 2020-01-24 09:53

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))
}
查看更多
再贱就再见
4楼-- · 2020-01-24 10:01

You can use De Morgaan's laws to rewrite an AND query as an OR query.

查看更多
神经病院院长
5楼-- · 2020-01-24 10:03

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)
查看更多
Anthone
6楼-- · 2020-01-24 10:08

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"]); 
查看更多
7楼-- · 2020-01-24 10:09

OR operator is not accepted in firebase firestore. 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

查看更多
登录 后发表回答