Assume a collection with schema like as shown below:
{
"customer" : <unique-id-for-customer>,
"purchase" : <number>,
}
Now, I want to get the the top 5 customers (by purchase-queantity) and the 6th bucket is "others" which combines all the purchase quantity from other customers.
Basically, the output of aggregation should be like:
{ "_id" : "customer100", "purchasequantity" : 4000000 }
{ "_id" : "customer5", "purchasequantity" : 81800 }
{ "_id" : "customer4", "purchasequantity" : 40900 }
{ "_id" : "customer3", "purchasequantity" : 440 }
{ "_id" : "customer1", "purchasequantity" : 300 }
{"_id" : "others", "purchasequantity" : 29999}
What you want is called weighting. To do that you need to add a weight to your documents by
$project
ing them and using the$cond
operator, then sort them by "weight" in ascending other and by "purchasequantity" in descending order.Which returns: