How can I get top buckets for aggregation and all other buckets combined in a “different” bucket?

Assume a collection with a schema as shown below:

{ "customer" : <unique-id-for-customer>, "purchase" : <number>, } 

Now I want to get the 5 best customers (at the purchase price), and the sixth bucket is “others”, which combines the total number of purchases from other customers.

In principle, the result of aggregation should be as follows:

 { "_id" : "customer100", "purchasequantity" : 4000000 } { "_id" : "customer5", "purchasequantity" : 81800 } { "_id" : "customer4", "purchasequantity" : 40900 } { "_id" : "customer3", "purchasequantity" : 440 } { "_id" : "customer1", "purchasequantity" : 300 } {"_id" : "others", "purchasequantity" : 29999} 
+5
source share
1 answer

What you want is called weighting . To do this, you need to add weight to your $project documents and use $cond , then sort them by "weight" in the upstream friend and "buyquantity" in descending order.

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

What 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 } 
+1
source

Source: https://habr.com/ru/post/1240312/


All Articles