mongo對分組數據進行排序


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM