根据时间戳从 MongoDB 集合中获取文档

Fetch documents from a MongoDB collection based on timestamp

我有一个 MongoDB 集合,其中包含如下所示的文档

{
    "_id" : ObjectId("5aab91b2caa256021558f3d2"),
    "Timestamp" : "2017-11-16T14:43:07.5357785+01:00",
    "status" : 1,
    "created_at" : 1521193394,
    "updated_at" : 1521193394,
    "deleted_at" : ""
}

数据每 15 分钟输入一次集合。使用纪元时间的 created_at 字段,我想找到一种在每小时顶部获取数据的方法。因此,例如,数据在 12.00 12.15 12.30 12.45 13.00 13.15 13.30 13.45 14.00 处输入。

我想从 12.00、13.00 和 14.00 输入的集合中获取条目。

我也乐于接受关于使用纪元时间是否是最好的解决方法的建议。

使用纪元时间确实是个好方法。

由于你是按秒计算的,所以每个圆小时都可以被3600整除(小时中的秒数)没有余数。您可以使用此 属性 来查找您的文档。

db.collection.find({created_at: {$mod: [ 3600, 0 ]}});

根据 $mod 文档,

Select documents where the value of a field divided by a divisor has the specified remainder

我们提供的除数为 3600,余数为 0。这应该符合您的期望。

要忽略秒数:

对于这个条件,mod(epoch, 3600)应该小于59。这个查询可以使用$expr of mongo 3.6

组成
db.collection.find({$expr: {$lte: [{ $mod: [ '$created_at', 3600 ] }, 59]}});

希望对您有所帮助!