英文:
aggregate group by time of intervals of 15 minutes
问题
我正在尝试计算数据的平均速度,时间间隔为15分钟。我得到了结果,其中包含平均速度,但不确定是否正确以及是否针对15分钟的数据集,还有minutes
是空的。
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格式和Date类型。
谢谢。
英文:
I'm trying to calculate average speed of data for 15 minutes. I get the result back, it contains average speed, but not sure it's correct and for 15 minute sets, also minutes
is 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",
},
},
}
Anyone done something similar or can help?
EDIT: $timestamp field is ISODate format and Date type
Thank you
答案1
得分: -1
在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()
请注意,这只是一个翻译,我无法保证这段代码的正确性。
英文:
Running the following pipeline in mongo shell should give you the correct result:
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)
of which the equivalent mGo expression follows (untested):
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论