GusRuss89
GusRuss89

Reputation: 1404

In Firestore, how can I query items created within a date range and order by a different field?

I'm trying to create a query for "top posts of the last week/month/year". I thought it would be simple, but I'm running into limitations with Firestore's querying rules.

Here's the query I'd ideally like to run:

db
  .collection(MY_COLLECTION)
  .where('created', '>', new Date(fromDate))
  .orderBy('score', 'desc')

That gives me this error:

FirebaseError: Invalid query. You have a where filter with an inequality (<, <=, >, or >=) on field 'created' and so you must also use 'created' as your first Query.orderBy(), but your first Query.orderBy() is on field 'score' instead.

Is there a known strategy or workaround for these types of queries?

Upvotes: 0

Views: 170

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83153

To solve the error you are getting, you should first order by the created field, as follows:

db
  .collection(MY_COLLECTION)
  .where('created', '>', new Date(fromDate))
  .orderBy('created', 'desc')
  .orderBy('score', 'desc')

This is indicated in the documentation:

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

Note that you will need to create an index for this query. For that, just run the query once and in the error message that you will get you will find the URL to call in order to create the index.


If you want to query for all documents between two dates, you can use a query like:

db
  .collection(MY_COLLECTION)
  .where('created', '>', new Date(fromDate))
  .where('created', '<=', new Date(toDate))
  .orderBy('created', 'desc')
  .orderBy('score', 'desc')

Upvotes: 1

Related Questions