我找不到任何这方面的例子,所以我不确定这是否可行。我有以下文件
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
答案 0 :(得分:5)
我让它使用这个管道。
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])