MongoDB聚合总和嵌套数字数组

时间:2021-06-02 22:12:45

标签: javascript arrays mongodb mongoose aggregation-framework

我有以下文档结构

{
            "_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。我做错了什么?

2 个答案:

答案 0 :(得分:0)

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。 :)

答案 1 :(得分:0)

你可以这样做:

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

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