【问题标题】:MongoDB Aggregate sum nested number arrayMongoDB聚合和嵌套数字数组
【发布时间】:2021-08-21 02:06:00
【问题描述】:

我有以下文档结构

{
            "_id": "60b7b7c784bd6c2a1ca57f29",
            "user": "607c58578bac8c21acfeeae1",
            "exercises": [
                {
                    "executed_reps": [8,7],
                    "_id": "60b7b7c784bd6c2a1ca57f2a",
                    "exercise_name": "Push up"
                },
                {
                    "executed_reps": [5,5],
                    "_id": "60b7b7c784bd6c2a1ca57f2b",
                    "exercise_name": "Pull up"
                }
            ],
        }

在聚合中,我尝试对所有 executed_reps 求和,因此本示例中的最终值应为 25 (8+7+5+5)。

这是我目前的代码:

const exerciseStats = await UserWorkout.aggregate([
    {
        $match: {
            user: { $eq: ObjectId(req.query.user) },
        },
    },
    { $unwind: '$exercises' },
    {
        $group: {
            _id: null,
            totalReps: {
                $sum: {
                    $reduce: {
                        input: '$exercises.executed_reps',
                        initialValue: '',
                        in: { $add: '$$this' },
                    },
                },
            },
        },
    },
]);

totalReps 的结果为 5。我做错了什么?

【问题讨论】:

    标签: javascript arrays mongodb mongoose aggregation-framework


    【解决方案1】:

    10 分钟后我自己找到了解决方案:

    UserWorkout.aggregate([
        {
            $match: {
                user: { $eq: ObjectId(req.query.user) },
            },
        },
        { $unwind: '$exercises' },
        {
            $project: {
                total: { $sum: '$exercises.executed_reps' },
            },
        },
        {
            $group: {
                _id: null,
                totalExercises: { $sum: '$total' },
            },
        },])
    

    必须先使用 $project。 :)

    【讨论】:

      【解决方案2】:

      你可以这样做:

      const exerciseStats = await UserWorkoutaggregate([
        {
          "$addFields": {
            "total": {
              "$sum": {
                "$map": {
                  "input": "$exercises",
                  "as": "exercise",
                  "in": {
                    "$sum": "$$exercise.executed_reps"
                  }
                }
              }
            }
          }
        }
      ])
      

      下面是工作示例:https://mongoplayground.net/p/5_fsPgSh8EP

      【讨论】:

        猜你喜欢
        • 2017-07-26
        • 2020-11-09
        • 1970-01-01
        • 1970-01-01
        • 2021-12-31
        • 2021-06-27
        • 2015-12-06
        • 1970-01-01
        • 2021-04-19
        相关资源
        最近更新 更多