【问题标题】:MongoDB Aggregation: How to group an array of objects get the multiple of the groups then sum the multiplesMongoDB聚合:如何对对象数组进行分组获取组的倍数,然后将倍数相加
【发布时间】:2020-12-15 09:59:02
【问题描述】:

文件

[    
    { _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" }

【问题讨论】:

    标签: arrays mongodb mongodb-query aggregation-framework


    【解决方案1】:

    这个怎么样?

    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
            }
        } } } }
    ])
    

    【讨论】:

      猜你喜欢
      • 2015-04-01
      • 2023-01-20
      • 1970-01-01
      • 1970-01-01
      • 2018-04-20
      • 2021-07-13
      • 2021-06-21
      • 1970-01-01
      • 2018-08-17
      相关资源
      最近更新 更多