以15分钟为间隔的时间汇总组

This question already has an answer here:

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

</div>

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()