如何从Firebase获取按时间戳排序的文档查询?

huangapple go评论107阅读模式
英文:

How to get a query of documents from Firebase, sorting by timestamps?

问题

在我的应用程序中,用户可以上传包含时间戳的文档到Cloud Firestore。这些文档构成了用户文档中的一个子集合,用于跟踪他们在应用程序中的每一天的统计数据。我希望能够从数据库中检索这些文档的查询,类似于使用collection.orderBy的方式。

但我最好能够在多个不同的时间范围之间进行排序。例如,我想要能够对所有时间戳匹配于7月16日的文档进行排序。是否有实现这个目标的方法?谢谢。

英文:

In my app, users can upload documents to Cloud Firestore containing a timestamp. These documents make up a subcollection in the user's document, tracking their day by day statistics in the app. I want to be able to retrieve a query of these documents from the database, using something like collection.orderBy.

I'd ideally like to sort between multiple different time frames though. For example, I'd like to be able to sort through all of the documents whose timestamps match July 16th. Is there a way to accomplish this? Thank you.

答案1

得分: 0

You can use a range query with the timestamp field. You will have to provide the start and end points for the query.

firestore
    .collection("your-collection")
    .whereGreaterThan("timestamp", start)
    .whereLessThan("timestamp", end)
    .orderBy("timestamp")

timestamp is the name of your timestamp field. start and end must be Date or Timestamp objects. If the period of time is just one day, then you will need to build start and end around that day. In your specific case, perhaps midnight July 16 and midnight July 17 might make a good boundary, but it's up to you.

英文:

You can use a range query with the timestamp field. You will have to provide the start and end points for the query.

firestore
    .collection("your-collection")
    .whereGreaterThan("timestamp", start)
    .whereLessThan("timestamp", end)
    .orderBy("timestamp")

timestamp is the name of your timestamp field. start and end must be Date or Timestamp objects. If the period of time is just one day, then you will need to build start and end around that day. In your specific case, perhaps midnight July 16 and midnight July 17 might make a good boundary, but it's up to you.

huangapple
  • 本文由 发表于 2020年7月28日 10:24:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/63126134.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定