juanbits
juanbits

Reputation: 347

Get documents between two dates

In my collection I have some documents and one of their values is the created_on key, that is filled by timestamp at the creation of the document.

I want to retrieve the documents created between two dates, but I can't get it in a simple way, i have the next:

FOR d IN mycollection
FILTER '2021-12-01' <= DATE_FORMAT(d.created_on, "%yyyy-%mm-%dd") <= '2021-12-05'
SORT d.created_on ASC 
RETURN DATE_FORMAT(d.created_on, "%yyyy-%mm-%dd")

but the above query returns all the records, not only the documents that are in the specified time period.

Any suggestions? Thanks in advance!

Upvotes: 0

Views: 679

Answers (1)

mpoeter
mpoeter

Reputation: 2949

The problem is your filter expression '2021-12-01' <= DATE_FORMAT(d.created_on, "%yyyy-%mm-%dd") <= '2021-12-05' This is basically the same as

LET x = '2021-12-01' <= DATE_FORMAT(d.created_on, "%yyyy-%mm-%dd")
FILTER x <= '2021-12-05'

x is a bool and as such always compares less than a string.

You should rewrite your query as follows:

FOR d IN mycollection
  LET date = DATE_FORMAT(d.created_on, "%yyyy-%mm-%dd")
  FILTER '2021-12-01' <= date AND date <= '2021-12-05'
  SORT d.created_on ASC 
  RETURN DATE_FORMAT(d.created_on, "%yyyy-%mm-%dd")

This should filter correctly, but you won't be able to utilize any indexes on created_an for the FILTER, only for the SORT. So instead it would be better to write the query as follows:

LET from = DATE_TIMESTAMP('2021-12-01')
LET to = DATE_TIMESTAMP('2021-12-05')
FOR d IN mycollection
  FILTER from <= d.created_on AND d.created_on <= to
  SORT d.created_on ASC 
  RETURN DATE_FORMAT(d.created_on, "%yyyy-%mm-%dd")

Upvotes: 1

Related Questions