如果你想首先按照货币进行排序,那么你应该将排序更改为 -
{"$sort": {"_id.currency": 1, "total": -1}}
。排序顺序由你指定键的顺序驱动。
以下是我创建的示例文档 -
{ "_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 } }
查询语句 - 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}}])
输出结果为 -
{
"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
}
对于查询 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}}])
的输出结果为 -
{
"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
}
currency
的数据类型是什么?你能发布一份你的收藏中的示例文档吗? - Anand Jayabalan