If you want the sorting to happen by Currency first, then you should change your sort to - {"$sort": {"_id.currency": 1, "total": -1}}
. The sorting order is driven by the order in which you specify the keys.
These are the sample documents that I created -
{ "_id" : ObjectId("533dc9d272337e43d14600f7"), "_cls" : "class1", "v_id" : 6813, "total" : { "amount" : 680, "currency" : "EUR", "exp" : -2 } }
{ "_id" : ObjectId("533dc9d972337e43d14600f8"), "_cls" : "class1", "v_id" : 6813, "total" : { "amount" : 690, "currency" : "EUR", "exp" : -2 } }
{ "_id" : ObjectId("533dc9de72337e43d14600f9"), "_cls" : "class1", "v_id" : 6813, "total" : { "amount" : 690, "currency" : "USD", "exp" : -2 } }
{ "_id" : ObjectId("533dc9e672337e43d14600fa"), "_cls" : "class1", "v_id" : 6813, "total" : { "amount" : 680, "currency" : "USD", "exp" : -2 } }
{ "_id" : ObjectId("533dcd0172337e43d14600fb"), "_cls" : "class1", "v_id" : 6813, "total" : { "amount" : 2000, "currency" : "CHE", "exp" : -2 } }
{ "_id" : ObjectId("533dcdfb72337e43d14600fc"), "_cls" : "class1", "v_id" : 6814, "total" : { "amount" : 2000, "currency" : "CHE", "exp" : -2 } }
{ "_id" : ObjectId("533dce1572337e43d14600fd"), "_cls" : "class1", "v_id" : 6815, "total" : { "amount" : 1000, "currency" : "CHE", "exp" : -2 } }
for query - db.sample4.aggregate([{"$match": {"_cls": "class1"}},{$group:{"_id":{"currency":"$total.currency","v_id":"$v_id"},"total":{$sum:"$total.amount"}}},{"$sort": {"_id.currency": 1, "total": -1}}])
output is -
{
"result" : [
{
"_id" : {
"currency" : "CHE",
"v_id" : 6814
},
"total" : 2000
},
{
"_id" : {
"currency" : "CHE",
"v_id" : 6813
},
"total" : 2000
},
{
"_id" : {
"currency" : "CHE",
"v_id" : 6815
},
"total" : 1000
},
{
"_id" : {
"currency" : "EUR",
"v_id" : 6813
},
"total" : 1370
},
{
"_id" : {
"currency" : "USD",
"v_id" : 6813
},
"total" : 1370
}
],
"ok" : 1
}
for query db.sample4.aggregate([{"$match": {"_cls": "class1"}},{$group:{"_id":{"currency":"$total.currency","v_id":"$v_id"},"total":{$sum:"$total.amount"}}},{"$sort": {"_id.currency": 1, "total": 1}}])
output is -
{
"result" : [
{
"_id" : {
"currency" : "CHE",
"v_id" : 6815
},
"total" : 1000
},
{
"_id" : {
"currency" : "CHE",
"v_id" : 6814
},
"total" : 2000
},
{
"_id" : {
"currency" : "CHE",
"v_id" : 6813
},
"total" : 2000
},
{
"_id" : {
"currency" : "EUR",
"v_id" : 6813
},
"total" : 1370
},
{
"_id" : {
"currency" : "USD",
"v_id" : 6813
},
"total" : 1370
}
],
"ok" : 1
}