如何在MongoDB中的文档中添加数组?
e.g:
{"_id":1, "a":[1,2,3,4]}
{"_id":2, "a":[3,4,5,6]}
结果:
{"sum":[4,6,8,10]}
答案 0 :(得分:0)
请尝试完成aggregation
> db.collection.aggregate([
// 1. unwind the array a with this array index
{$unwind: {path: '$a', includeArrayIndex: 'index'}},
// 2. sum them by their index
{$group: {
_id: '$index',
a: {$sum: '$a'}
}},
// 3. sort by array index
{$sort: {_id: 1}},
// 4. group them into the sum array
{$group: {_id: null, sum: {$push: '$a'}}}
])