Search code examples
mongodbaggregation-frameworkisodate

Best way to get documents in specific timeframe MongoDB


I am creating a script that would run after every x minutes and needs to gather data from MongoDB by timestamps.

For example, how would I match the documents with aggregation that have a timestamp in the following timeframe:

start_time = current_time - 60 min
end_time = start_time + 30 min

And I would need to get all the documents that stay within that time frame. The MongoDB objects have ISODate timestamps on them.

Thanks!


Solution

  • You can create date objects in mongo shell like so:

    db.getCollection('order').aggregate([
    {
    $match : { 
        start_time : {$gte :  new Date(ISODate().getTime() - 1000 * 60 * 60)},
        end_time : {$lte :  new Date(ISODate().getTime() + 1000 * 60 * 30)}
        }
    }
    ...
    ])
    

    You can use this in aggregate but also in normal find queries.

    Note I wrote this without testing, so it might have syntax errors..