2016-01-11 33 views
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} 
+0

我覺得這是不可能的只是一個彙總命令。 – dikesh

+2

我也盡我所能......找不到一種方式來檢索單個命令中的結果。 db.aggregations.aggregate([{$排序:{purchasequantity:-1}},{$極限:5}]);和db.aggregations.aggregate([{$ sort:{purchasequantity:-1}},{$ skip:5},{$ group:{_ id:'others',totalAmount:{$ sum:'$ purchasequantity'}} }]);結果必須合併。 – harshavmb

+0

第一聚合: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

回答

1

你想要什麼叫weighting。要做到這一點,您需要通過$project加上文件的權重並使用$cond運算符,然後按照其中的「權重」按升序排序,按「purchasequantity」按降序排序。

db.collection.aggregate([ 
    { "$project": { 
     "purchasequantity": 1, 
     "w": { 
      "$cond": [ { "$eq": [ "$_id", "others" ] }, 1, 0 ] 
     } 
    }}, 
    { "$sort": { "w": 1, "purchasequantity": -1 } } 
]) 

將返回:

{ "_id" : "customer100", "purchasequantity" : 4000000, "w" : 0 } 
{ "_id" : "customer5", "purchasequantity" : 81800, "w" : 0 } 
{ "_id" : "customer4", "purchasequantity" : 40900, "w" : 0 } 
{ "_id" : "customer3", "purchasequantity" : 440, "w" : 0 } 
{ "_id" : "customer1", "purchasequantity" : 300, "w" : 0 } 
{ "_id" : "others", "purchasequantity" : 29999, "w" : 1 } 
相關問題