How can I get top n buckets for an aggregation and all other buckets combined into an “other” bucket?

后端 未结 1 1737
清酒与你
清酒与你 2021-01-12 16:55

Assume a collection with schema like as shown below:

{
    \"customer\" : ,
    \"purchase\" : ,
}
1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-12 17:53

    What you want is called weighting. To do that you need to add a weight to your documents by $projecting them and using the $cond operator, then sort them by "weight" in ascending other and by "purchasequantity" in descending order.

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

    Which returns:

    { "_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 }
    

    0 讨论(0)
提交回复
热议问题