我找不到任何相关的例子,所以我不确定是否可能。我有以下文件:
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