Firestore query by dates and times separately

2020-06-30 04:17发布

问题:

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.

It would go something like this:

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/{single event document}:

{
  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 }

回答1:

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

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

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

It is quite common to duplicate the data in an NoSQL database, in particular to allow querying according to your business needs.