分组之后希望按原字段进行排序,比如说时间戳,可以在分组数据中用$first显示原数据,然后在利用管道对该字段进行排序
参考:
db.xx.aggregate([
{"$match":{"timestamp": {"$gte":1557813600,"$lte":1560492000},"service":{"$in":["bauhinia","internal"]}}},
{
"$group":{
"_id":{"service":"$service","timestamp":"$timestamp"},
"flow":{$sum:{$multiply:["$rate","$count"]}},
"timestamp":{"$first":"$timestamp"},
},
},
{"$sort":{"timestamp":1}},
])
go语言代码参考
pipelines := []bson.M{
//如果 $match 位于管道的第一个阶段,可以利用索引来提高查询效率
{"$match": bson.M{"timestamp": bson.M{"$gte": float64(cursorTimeStamp), "$lte": float64(nowTimeStamp)},"service":bson.M{"$in":models.ServiceArr}}},
{"$group": bson.M{
"_id": bson.M{"service": "$service", "timestamp": "$timestamp"},
"flow": bson.M{"$sum": bson.M{"$multiply": []string{"$rate", "$count"}}},
//额外的timestamp用于排序
"timestamp":bson.M{"$first":"$timestamp"},
}},
{"$sort":bson.M{"timestamp":1}},
}