简体   繁体   中英

Get documents bewteen 2 dates

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

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 suggestion? thanks in advance

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM