分組之后希望按原字段進行排序,比如說時間戳,可以在分組數據中用$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}}, }