文档
[
{ _id: "a1",
selections:[
{_id:"s1", questionId:"q1", points:3, group:"no-group"},
{_id:"s2", questionId:"q2", points:2, group:"group-1"},
{_id:"s3", questionId:"q3", points:3, group:"no-group"},
{_id:"s4", questionId:"q4", points:7, group:"group-2"},
{_id:"s5", questionId:"q5", points:8, group:"group-2"},
{_id:"s6", questionId:"q6", points:9, group:"group-1"},
],
userId: "u1"
},
]我正在尝试创建一个聚合,它可以对对象数组进行分组,获取组的多个,然后对倍数进行求和。例如,对于上面给定的文档,分组数组如下所示:
[
[
{_id:"s1", questionId:"q1", points:3, group:"no-group"},
{_id:"s3", questionId:"q3", points:3, group:"no-group"},
],
[
{_id:"s2", questionId:"q2", points:2, group:"group-1"},
{_id:"s6", questionId:"q6", points:9, group:"group-1"},
],
[
{_id:"s4", questionId:"q4", points:7, group:"group-2"},
{_id:"s5", questionId:"q5", points:8, group:"group-2"},
],
]然后得到除group: "no-group"组外的所有组的倍数。用于"no-group"的值与它们之和,而不是得到它们的倍数。
例如,分组数组将导致:
[
[3+3],// for no-group sum the points
[2*9],// for group-1 multiply the points
[7*8],// for group-2 multiply the points
]
// output = [ 6, 18, 56 ]然后将输出6+18+56=80之和。
我如何在mongodb聚合中做到这一点?这样我就能得到如下的输出
{ userId:"u1", totalPoints:"80" }发布于 2020-12-15 10:34:43
这个怎么样?
db.getCollection('col1').aggregate([
{ $unwind: '$selections' }, // unwrap initial selections array
{ $group: { _id: { user: '$userId', group: '$selections.group' }, points: { $push: '$selections.points' } } }, // group by user and group
{ $group: { _id: '$_id.user', totalPoints: { $sum: { // get the total sum for...
$cond:{
if: { $eq: ['$_id.group', 'no-group'] },
then: { $sum: '$points'}, // the sum of points if no-group
else: { $reduce: { input: '$points', initialValue: 1, in: { $multiply: ['$$value', '$$this']} } } // the multiplication of points for rest of cases
}
} } } }
])https://stackoverflow.com/questions/65303614
复制相似问题