Skip to content
Advertisement

Query Firestore field/value using multiple multiple ‘where’ values?

I’m considering letting users follow other users in a app, and would have a feed of posts from people who they follow.

Is there a way to query multiple ‘where’ statements at once, or compare to a List? Or would a alternate route need to be taken?

Here is a example scenario in NodeJS:

var usersFollowed = ['GKXgK2CPPGPQjmQ3Lsrh', 'cBjzo3MSjjaOHksVmO0o', 'tc9gMwZR9SiyjWonyCWF'];

var followingPosts = await db.collection('posts').where('posterUID', '==', usersFollowed.Any()).get();

(.Any() is made up and what I would like to do)

Here is a example of a post’s document in Firestore:

postID
    caption: 'a picture of something'
    type: 'picutre'
    size: 1
    posterUID: GKXgK2CPPGPQjmQ3Lsrh

Advertisement

Answer

You should use the in operator: “Use the in operator to combine up to 10 equality (==) clauses on the same field with a logical OR. An in query returns documents where the given field matches any of the comparison values”.

var usersFollowed = ['GKXgK2CPPGPQjmQ3Lsrh', 'cBjzo3MSjjaOHksVmO0o', 'tc9gMwZR9SiyjWonyCWF'];
var followingPosts = await db.collection('posts').where('posterUID', 'in', usersFollowed).get();

However, note that you can only combine up to 10 equality (==) clauses.

If you need to combine more than 10 clauses, you will need to do several similar queries and merge the results. This article explains how to merge two queries with the JS SDK.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement