【问题标题】:Best way to get documents in specific timeframe MongoDB在特定时间范围内获取文档的最佳方法 MongoDB
【发布时间】:2017-10-24 15:44:10
【问题描述】:

我正在创建一个脚本,该脚本将在每 x 分钟后运行一次,并且需要按时间戳从 MongoDB 收集数据。

例如,我将如何匹配具有以下时间范围内时间戳的聚合文档:

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

而且我需要获取所有在该时间范围内的文件。 MongoDB 对象上有 ISODate 时间戳。

谢谢!

【问题讨论】:

    标签: mongodb aggregation-framework isodate


    【解决方案1】:

    您可以像这样在 mongo shell 中创建日期对象:

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

    您可以在聚合中使用它,也可以在正常的查找查询中使用它。

    注意我写的这个没有测试,所以它可能有语法错误..

    【讨论】:

    • 谢谢!正是我需要的!
    【解决方案2】:

    db.collection.find({"createdAt": { $gt: new Date('2017-04-25')},"updatedAt":{$lt:new Date('2017-06-25') }})

    updatedAt 和 createdAt 是我在按时间戳设计架构时所采用的字段。你可以根据你的设计给字段。

    在这种情况下,查找查询会比聚合好一点,因为不需要执行复杂的功能

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多