ARTICLE AD BOX
I am executing the following query on my MongoDB using the Java driver
private static AggregateIterable<Document> averageVendorTotalSent(MongoCollection<Document> collection) { return collection.aggregate(Arrays.asList( Aggregates.group("$transaction vendor", Accumulators.avg("Average Vendor Transaction Sent", "$amount sent")) )); }On a collection with Documents formatted like
_id: "69cb3d75c6146e2646e66330" date: "2026-02-17" transaction vendor: "TIM HORTONS #47 _F" amount sent: 11.21 amount received: 0 remainingBalance: 3269.39here is part of the output
{"_id": "SQ *THE TASTE O _F", "Average Vendor Transaction Sent": 25.82} {"_id": "HECTOR'S YOUR I", "Average Vendor Transaction Sent": 27.72} {"_id": "TIM HORTONS #47 _F", "Average Vendor Transaction Sent": 10.573142857142857} {"_id": "SSV TO: 89966442264", "Average Vendor Transaction Sent": 2.75} {"_id": "7 ELEVEN STORE _F", "Average Vendor Transaction Sent": 14.66} {"_id": "DOLLARAMA # 859 _F", "Average Vendor Transaction Sent": 3.64} {"_id": "CANADIAN TIRE # _F", "Average Vendor Transaction Sent": 43.65} {"_id": "WENDY'S RESTAUR _F", "Average Vendor Transaction Sent": 5.7875} {"_id": "DOORDASHWENDYS _V", "Average Vendor Transaction Sent": 21.525} {"_id": "HUSKY GAS STATI", "Average Vendor Transaction Sent": 68.73} {"_id": "ROCK AUTO 165.78_V", "Average Vendor Transaction Sent": 235.33} {"_id": "GARIBALDI GRAPH _F", "Average Vendor Transaction Sent": 9.92}It grabs all vendors and takes the average transaction amount.
I would like to now sort this data by that average value
I have spent a few hours experimenting trying to solve this problem,
I have explored the built in Sorts function for the driver but can't seem to find a way to sort with that that isn't based on a field name
and I explored the documentation for Projection during the aggregation pipeline but I don't think that is the route to take either.
I have considered just sorting it in Java after the fact but that feels hacky as I doubt this is something that there isn't either a best practice or a built in solution for.
How do I go about sorting by that non-field value in the aggregation pipeline, should I not be in an aggregation pipeline for this; should it just be done in Java, should I be creating a new Collection with this modified data and storing it in new documents? At this point I am not looking for someone to hand me the solution I would just appreciate someone to point me in the correct direction. If I have looked in the right place maybe just be a little bit more explicit with where I need to look.
Any help is appreciated.
