Skip to content Skip to sidebar Skip to footer

Firebase Date Range Query To Fetch Documents That Have Stardate And Enddate

I have a collection of tasks on my Firestore database like this: 'tasks': { v8NC4GovVOPe21fhwtp0 : { id: 'v8NC4GovVOPe21fhwtp0' status: 0 dateFrom: 30 a

Solution 1:

Firestore allows to chain multiple "where()" methods to create more specific queries but only on the same field. As you can probably see in the official documentation regardin Query limitations:

Cloud Firestore does not support the following types of queries:

  • Queries with range filters on different fields, as described in the previous section.

So range filters on different fields are forbidden.

To achieve what you want, you need to query your database twice, once to fiter data using a call to:

.whereGreaterThanOrEqualTo("dateFrom", startDate)

And second using a call to:

.whereLessThanOrEqualTo("dateTo", endDate)

But unfortunately you cannot use them in the same query.

Edit:

When we are designing a database schema, basically we structure it for our queries. So beside the above solution in which you can filter on one field in the query, and on the other field in your client-side code, there is also another approach in which you can combine the values of the two range into a single field in some way that will allow your use-case with a single field.

One of the most successful examples I've seen so far is the combination used in Geohashes to filter on latitude and longitude as explained by Frank van Puffelen in the following video:

Knowing the difference in effort between these two solutions, I'd recommend using the first one.

There is also a third solution, in which you should to add all tasks from Mar-Apr into a single collection. Then you could query this new collection with:

 db.collection("tasks-aps-mar")
    .whereGreaterThanOrEqualTo("day", 1)
    .whereLessThanOrEqualTo("day", 30);

Even a more general solution would be to store the tasks in a collection for each month, and then perform a query to get all the tasks that correspond with the desired month. In your use case, you should query your database to get the documents within one of each collection tasks-mar-2019, tasks-apr-2019, tasks-may-2019 and so on.

Regarding your comment, using arrays won't help you at all since you cannot use range intervals.

Post a Comment for "Firebase Date Range Query To Fetch Documents That Have Stardate And Enddate"