LoginSignup
1
1

More than 3 years have passed since last update.

CloudFirestoreで降順データをクエリの開始点と終了点で絞り込む時の注意点

Posted at

やりたいこと

Firestoreに登録しているデータを日付の期間指定で絞り込みをしたい。
RDBでお馴染みの標準SQLで言うところの下記。

select ...
from ...
where CREATE_AT between date1 and date2
order by CREATE_AT desc

結果

1. まずは普通に期間指定 ...できました。

orderBy("CREATE_AT").startAt(date1).endAt(date2)

2. 続いて降順 ...検索結果が0件になってしまいました。

orderBy("CREATE_AT", "desc").startAt(date1).endAt(date2)
                      ^^^^^

正解

orderBy("CREATE_AT", "desc").startAt(date2).endAt(date1)
                                     ^^^^^        ^^^^^

上記のように、範囲指定を大きい日付から小さい日付に入れ替えることで抽出することができました。
まず降順にソートされてから範囲指定するため、大きい日付を先に設定しないといけないのですね。

原因が分かってから改めてコードを見れば、先にソートがかかるので当たり前なのですが、SQLの構文に慣れていると無意識に「範囲指定→ソート」と考えてしまい、地味にハマりました。

参考

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1