MongoDB每秒获取结果 [英] MongoDB get every second result

查看:65
本文介绍了MongoDB每秒获取结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MongoDB中,所有文档都有一个日期字段,它是一个时间戳.

In MongoDB all documents have a date field, it is a timestamp.

有很多数据,我想在每个间隔中只获取其中的一部分:

There is a lot of data, and I want to get only some part of it, for every interval:

例如400毫秒

1402093316030<----
1402093316123
1402093316223
1402093316400<----
1402093316520
1402093316630
1402093316824<----

是否有可能获得彼此的结果,或者获得每三分之一的结果? 还是最好每400毫秒发送一次文档?

Is it possible to get every other, or every third result? Or better first document every 400 ms?

推荐答案

您可以使用聚合框架和一些日期数学来做到这一点.假设您有一个时间戳"字段和其他字段"a","b"和"c":

You can do this with the aggregation framework and a little date math. Let's say you have a "timestamp" field and addtional fields "a", "b" and "c":

db.collection.aggregate([
    { "$group": {
        "_id": {
            "$subtract": [
                "$timestamp",
                { "$mod": [ "$timestamp", 400 ] }
            ]
        },
        "timestamp": { "$first": "$timestamp" },
        "a": { "$first": "$a" },
        "b": { "$first": "$b" },
        "c": { "$first": "$c" }
    }}
])

因此,日期数学以400ms的间隔分组"时间戳"字段的值.其余数据通过 $first 进行标识> 运算符,该运算符从在这些分组边界上找到的字段中选择最后一个"值.

So the date math there "groups" on the values of the "timestamp" field at 400ms intervals. The rest of the data is identified with the $first operator, which picks the "last" value from the field as found on those grouping boundaries.

如果您不希望在这些边界上使用最后一个"项目,则可以使用

If you otherwise wan the "last" item on those boundaries then you switch to use the $lastoperator instead.

最终结果是每400毫秒间隔出现的最后一个文档.

The end result is the last document that occurred every 400 millisecond interval.

请参见聚合命令和聚合框架运算符以获取更多参考.

See the aggregate command and the Aggregation Framework operators for additional reference.

这篇关于MongoDB每秒获取结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆