我找不到任何这样的例子,所以我不确定这是否可能。我有以下文件
db.mytest.insert([
{ date: new Date('2013-06-01'),
account: 'A',
ids: [ { id: '1vb', sale: 50 }, { id: 'xy2', sales: 25 } ]
},
{ date: new Date('2013-06-02'),
account: 'A',
ids: [ { id: '1vb', sales: 10 }, { id: 'xy2', sales: 5 } ]
}
])
我正在尝试获得以下结果
[{ account: 'A':
ids: [ { id: '1vb', salesAmount: 60, salesCount: 8 },
{ id: 'xy2', salesAmount: 30, salesCount: 3 }
]
}]
我试过以下管道
var unwind = { $unwind: '$ids' };
var group = { $group: {
_id: { id: '$ids.id' },
ids: { $addToSet:
{
salesAmount: { $sum: '$ids.salesAmount' },
salesCount: { $sum: '$ids.salesCount' }
}
}
}};
db.mytest.aggregate([unwind, group])
但它正在返回此错误
Error: Printing Stack Trace
at printStackTrace (src/mongo/shell/utils.js:37:7)
at DBCollection.aggregate (src/mongo/shell/collection.js:897:1)
at (shell):1:11
Sun Jul 7 18:53:26.177 JavaScript execution failed: aggregate failed: {
"errmsg" : "exception: invalid operator '$sum'",
"code" : 15999,
"ok" : 0
} at src/mongo/shell/collection.js:L898
最佳答案
我让它与这条管道一起工作。
var unwind = { "$unwind" : "$ids" };
var group = {
"$group" : {
"_id" : {
"account" : "$account",
"id" : "$ids.id"
},
"idSalesAmount" : {
"$sum" : "$ids.salesAmount"
},
"idSalesCount" : {
"$sum" : "$ids.salesCount"
}
}};
var group2 = {
"$group" : {
"_id" : "$_id.account",
"ids" : {
"$addToSet" : {
"id" : "$_id.id",
"salesAmount" : "$idSalesAmount",
"saleCount" : "$idSalesCount"
}
}
}};
var project = { "$project" : { "account" : "$_id", "ids" : 1, "_id" : 0 } };
db.mytest.aggregate([unwind, group, group2, project])
关于mongodb 聚合 addToSet 与 sum,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17517205/