Work with dates and timezones

Take a look at $expr operator - it allows you to use aggregation expressions in $match stage or find command.

Like this:

db.tz.find({$expr:{$eq:[0, {$hour:{date:new Date(), tz:"$tz"}}]}})
{ "_id" : "Joe", "tz" : "Europe/Dublin" }

This finds all users for whom the time now is between midnight and 1am (aka hour=0).

wouldn’t it be very heavy query to execute aggregation for every single document

Well, if you need to query by something, then you query by it. If you are able to constrain the results by another field that could be indexed, then it would help, otherwise, it’s like any other collection scan - not optimal and if this is a large collection and this query needs to run frequently I would recommend figuring out how you can index this query.

5 Likes