Achive Archive
Achive Archive

Reputation: 33

mongodb aggregate documents by dates nearest to specific hour/minute in day

I have documents in my mongodb, this documents have event field - this fild type is date. The year, month , day, does not matter, means only the time during day. I want the cron script,every day, to aggregate from mongodb the documents with the event (date typed) field to be in nearest 10 minutes (to the script calling date). How to implement it in right way?

Upvotes: 1

Views: 839

Answers (1)

Chris Nauroth
Chris Nauroth

Reputation: 9844

db.mytable.find(
    {
        "event": {
            $gt: new Date(new Date().getTime() - (10 * 60 * 1000))
        }
    })

This query will find all documents that have an "event" property with a value within the past 10 minutes. new Date() without arguments returns a Date representing "right now". We pull the numeric epoch time in milliseconds from that and subtract 10 minutes. More specifically, we subtract (10 minutes * 60 seconds per minute * 1000 milliseconds per second), so that we convert to the correct units. We then use that value to construct another new Date(...), and this is the one that goes into the $gt (greater-than) filtering condition.

You mentioned a need for "aggregation". If so, then this same query can also be used within any Aggregation Pipeline that you need.

Upvotes: 1

Related Questions