This question already has answers here:
Group result by 15 minutes time interval in MongoDb

(5个答案)


4年前关闭。




我正在尝试计算15分钟的平均数据速度。我得到的结果是,它包含平均速度,但不确定是否正确,并且对于15分钟的设置,minutes也为nil。
o3 := bson.M{
    "$group": bson.M{
        "_id": bson.M{
            "minute": bson.M{
                "$subtract": []interface{}{
                    "$timestamp",
                    bson.M{
                        "$mod": []interface{}{
                            "$minute",
                            15,
                        },
                    },
                },
            },
        },
        "averageSpeed": bson.M{
            "$avg": "$speed",
        },
    },
}

任何人都做过类似的事情或可以提供帮助吗?

编辑:$ timestamp字段是ISODate格式和日期类型

谢谢

最佳答案

在mongo shell中运行以下管道应该会给您正确的结果:

pipeline = [
    {
        "$group": {
            "_id": {
                "year": { "$year": "$timestamp" },
                "dayOfYear": { "$dayOfYear": "$timestamp" },
                "minute_interval": {
                    "$subtract": [
                        { "$minute": "$timestamp" },
                        { "$mod": [{ "$minute": "$timestamp" }, 15] }
                    ]
                }
            },
            "averageSpeed": { "$avg": "$speed" }
        }
    }
]
db.collection.aggregate(pipeline)

其中等效的mGo表达式如下(未经测试):
pipeline := []bson.D{
    bson.M{
        "$group": bson.M{
            "_id": bson.M{
                "year": bson.M{ "$year": "$timestamp" },
                "dayOfYear": bson.M{ "$dayOfYear": "$timestamp" },
                "minute_interval": bson.M{
                    "$subtract": []interface{}{
                        bson.M{ "$minute": "$timestamp" },
                        bson.M{ "$mod": []interface{}{ bson.M{ "$minute": "$timestamp" }, 15, }, } }
                    }
                }
            },
            "averageSpeed": bson.M{ "$avg": "$speed" }
        }
    }
}

pipe := collection.Pipe(pipeline)
iter := pipe.Iter()

关于mongodb - 以15分钟为间隔的时间汇总组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35861602/

10-10 18:29
查看更多