Firestore按日期和时间分别查询 [英] Firestore query by dates and times separately
问题描述
如何按特定的日期和时间范围查询文档? IE.我想按特定日期范围(01-01-2019-31-01-2019)查询文档,并且从这些日期开始仅查询上午10点至下午12点的文档.
How do I query my documents by specific date and time range? Ie. I want to query documents by specific date range (01-01-2019 - 31-01-2019) and from those dates only the documents which are made in 10am to 12pm.
它会是这样的:
let ref = db.collection('events')
// Query by date range
ref = ref
.where('created', '>=', new Date(2019, 1, 1, 10, 0, 0, 0))
.where('created', '<=', new Date(2019, 1, 1, 12, 0, 0, 0))
// Query by time range in each date
ref = ref
.where('created', '>=', *START TIME = 10pm*)
.where('created', '<=', *END TIME = 12pm*)
所以问题是我每天如何过滤查询的小时和分钟?希望你理解我在这里要问的问题!如有需要,我将更新问题.
So the question is how do I filter hours and minutes every day I queried? Hopefully you understand what I'm asking here! I'll update the question if needed.
更新 数据库结构正在关注
Update Database sturcture is following
/events/{单个事件文档}:
{
cafeId: String,
created: Firestore timestamp // ex. February 2, 2019 at 10:16:00 AM UTC+2
discount: Number,
eventId: Number,
productCount: Number,
keywords: Array,
products: Map,
payment: Map,
returned: Number,
total: Number
}
当我在客户端创建此文件时,它将转换为:
And when I get this in the client created will transform to:
{ _seconds: Number, _nanoseconds: 0 }
推荐答案
如果要使用标准" where()
方法,则可能必须对前端的第二个过滤进行第二次过滤,以
If you want to use "standard" where()
methods, you'll probably have to do the second filtering on your front end, from the results received with
ref = ref
.where('created', '>=', new Date(2019, 1, 1, 10, 0, 0, 0))
.where('created', '<=', new Date(2019, 3, 1, 12, 0, 0, 0))
另一种方法是在一个额外的字段(例如createdText
)中以自定义格式(例如YYYYMMDDHHMM
)将日期/时间值存储为小时(例如HH)以24小时格式
Another approach would be to store, in an extra field (e.g. createdText
), your date/time value with a custom format, like for example YYYYMMDDHHMM
, with a 24 hours format for the hours (i.e. HH).
这样,文档将被正确排序,并且您只能使用一个where
进行查询,如下所示:
This way the document will be correctly sorted and you can query with only one where
, as follows:
ref = ref
.where('createdText', '>=', '201902031000')
.where('createdText', '<=', '201902041200')
在NoSQL数据库中复制数据非常普遍,尤其是允许根据您的业务需求进行查询.
It is quite common to duplicate the data in an NoSQL database, in particular to allow querying according to your business needs.
这篇关于Firestore按日期和时间分别查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!