我的集合中有这样的数据:
{
"_id" : ObjectId("5b29fc8a0d206c33115cdf87"),
"Cost" : 20,
"Desc" : "Cost of purchase",
"Category" : "C1",
"Vendor" : "Vendor 2"
}
{
"_id" : ObjectId("5b29fc8a0d206c33115cdf88"),
"Cost" : 40,
"Desc" : "Cost of repairs",
"Category" : "C1",
"Vendor" : "Vendor 1",
}........ so on
我想对此进行嵌套聚合以获取数据并在供应商上进行排序,如下所示:
[
{
"_id": "Cost of purchase",
"Value": [
{
"Vendor": "Vendor 1",
"Sum_Cost": 40
},
{
"Vendor": "Vendor 2",
"Sum_Cost": 20
}
]
}
]
但我没有对供应商的数据进行排序。我得到的数据如下:
[
{
"_id": "Cost of purchase",
"Value": [
{
"Vendor": "Vendor 2",
"Sum_Cost": 20
},
{
"Vendor": "Vendor 1",
"Sum_Cost": 40
}
]
}
]
这是我迄今为止完成的代码,通过对 Desc 和 Vendor 进行嵌套分组来获取成本总和。但我的排序不起作用,因为它假设使用供应商对对象数组内的数据进行排序:
let aggreArray = [{
$group: {
_id: {
Desc: "$Desc",
Vendor: "$Vendor"
},
sum: {
"$sum": "$Cost"
}
}
}, {
$group: {
_id: "$_id.Desc",
Value: {
$push: {
Vendor: "$_id.Vendor",
value: "$sum"
}
}
}
},{
$sort: { "Value.Vendor": 1}
}];
db.collection.aggregate(aggreArray).toArray(function (err, docs) {
console.log(docs);
});
最佳答案
我发现@Ashh的解决方案有效,但只是为了说清楚,以便我们知道这个问题已经有了解决方案,而不是从评论中阅读,我添加了这个答案。
let aggreArray = [{
$group: {
_id: {
Desc: "$Desc",
Vendor: "$Vendor"
},
sum: {
"$sum": "$Cost"
}
}
},
{ $sort: { "Value.Vendor": 1} },
{
$group: {
_id: "$_id.Desc",
Value: {
$push: {
Vendor: "$_id.Vendor",
value: "$sum"
}
}
}
}];
db.collection.aggregate(aggreArray).toArray(function (err, docs) {
console.log(docs);
});
基于 @Ashh 在评论部分的回答。
关于node.js - Mongoose 嵌套 group by 对嵌套字段进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50983522/