Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query one field then order by another one in Firebase cloud Firestore?

I'm struggling to make a (not so) complex query in firebase cloud firestore.

I simply need to get all docs where the id field == a given id.

Then order the results by their date and limit to 10 results.

So this is my current situation

db.firestore().collection('comments')
        .where("postId",'==',idOfThePost)
        .orderBy('date','asc').limit(10).get().then( snapshot => {
           //Nothing happens and the request wasn't even been executed
         })

I can get the result only if i don't use the orderBy query but i have to process this sorting for the needs of my application.

Someone has an idea to help me to fix this ?

thanks

like image 928
John doe Avatar asked Nov 02 '17 01:11

John doe


People also ask

How do I query multiple values in firestore?

With the in query, you can query a specific field for multiple values (up to 10) in a single query. You do this by passing a list containing all the values you want to search for, and Cloud Firestore will match any document whose field equals one of those values.

How do I aggregate data in firestore?

If you want to gain insight into properties of the collection as a whole, you will need aggregation over a collection. Cloud Firestore does not support native aggregation queries. However, you can use client-side transactions or Cloud Functions to easily maintain aggregate information about your data.


2 Answers

You can do this by creating an Index in the firestore.

The first field of the index should be the equality field and the second field of the index should be the order by field.

Given your problem, you would need the following index:

first field: postId, 'asc'
second field: date, 'asc'
like image 114
K Vij Avatar answered Oct 03 '22 06:10

K Vij


Please check the doc. It says

However, if you have a filter with a range comparison (<, <=, >, >=), your first ordering must be on the same field

you can try this code

db.firestore().collection('comments')
    .where("postId",'==',idOfThePost)
    .orderBy('postId')
    .orderBy('date','asc').limit(10).get().then( snapshot => {
       .....
     })
like image 38
Hareesh Avatar answered Oct 03 '22 04:10

Hareesh