5
承擔與架構集合類似如下圖所示:如何獲得聚合的前n個桶以及組合爲「其他」桶的所有其他桶?
{
"customer" : <unique-id-for-customer>,
"purchase" : <number>,
}
現在,我想獲得前五名客戶(按購置queantity)和第6桶是「其他」它結合了所有的採購數量來自其他客戶。
基本上,聚集的輸出應該是這樣的:
{ "_id" : "customer100", "purchasequantity" : 4000000 }
{ "_id" : "customer5", "purchasequantity" : 81800 }
{ "_id" : "customer4", "purchasequantity" : 40900 }
{ "_id" : "customer3", "purchasequantity" : 440 }
{ "_id" : "customer1", "purchasequantity" : 300 }
{"_id" : "others", "purchasequantity" : 29999}
我覺得這是不可能的只是一個彙總命令。 – dikesh
我也盡我所能......找不到一種方式來檢索單個命令中的結果。 db.aggregations.aggregate([{$排序:{purchasequantity:-1}},{$極限:5}]);和db.aggregations.aggregate([{$ sort:{purchasequantity:-1}},{$ skip:5},{$ group:{_ id:'others',totalAmount:{$ sum:'$ purchasequantity'}} }]);結果必須合併。 – harshavmb
第一聚合:db.test.aggregate([ \t { \t \t 「$排序」:{ 「購買」:-1} \t}, \t { \t \t 「$項目」:{ \t \t \t _id:'$顧客, \t \t \t '購買':1 \t \t} \t}, \t { \t \t $限額:5 \t} ]) 二次聚集:db.test.aggregate([ \t { \t \t 「$排序」:{ 「購買」:-1} \t}, \t { \t \t $跳過:5 \t}, \t { \t \t 「$組」:{ \t \t \t _id: '其他', \t \t \t '購買':{$和: 「$購買」} \t \t} \t} ]) – dikesh