Ciò che descrivi è la ponderazione: classifica ciò che vuoi mantenere prima del bucket che vuoi comprimere.
Aggiungi un peso $projectando i documenti con un $cond che marca la riga "others", poi ordina per peso crescente e per quantità decrescente:
db.collection.aggregate([ { "$project": { "purchasequantity": 1, "w": { "$cond": [ { "$eq": [ "$_id", "others" ] }, 1, 0 ] } }}, { "$sort": { "w": 1, "purchasequantity": -1 } } ])
Che restituisce:
{ "_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 }
Perché il sort a due chiavi funziona
Entro w: 0 l'ordinamento è interamente per purchasequantity decrescente, quindi i tuoi bucket reali escono dal più grande al più piccolo. La riga sintetica "others" porta w: 1 ed è quindi costretta in fondo indipendentemente dalla quantità — che è ciò che vuoi, perché un totale aggregato grande altrimenti si ordinerebbe nel mezzo della lista.
Se preferisci costruire il bucket "others" nella stessa aggregazione invece di dare per scontato che esista già, $facet con un ramo $limit e un ramo $skip-più-$group lo fa in un solo passaggio. E $setWindowFields su MongoDB 5.0 può classificare senza alcun campo peso manuale.