我的文档如下所示:

{
  "_id": "2023-04-08",
  "dailyNotes": [
    {
      "therapyDiscipline": "PT",
      "individual": [
        60,
        45,
        30,
        75,
        55
      ],
      "concurrent": [
        69
      ],
      "coTreat": [
        67
      ]
    }
  ]
}

我想要sum all numbers inside 100 array and create a new doc with only 100 key having the sum of array.

以下是我到目前为止try 过的方法,但没有奏效

{
$group: 
{
  _id: '$_id',
  individual:{
    $sum: '$dailyNotes.individual'
  }
}
}

这将返回:

{
  "_id": "2023-04-08",
  "individual": 0
}

一百零二

我try 过的其他解决方案很少,但它们也得出了0和:

{
$project: {
  individual: {
    $reduce: {
        input: "$dailyNotes.individual", 
        initialValue: 0,
        in: { $sum: [ "$$value", "$$this" ]}
    }
  }
}
}
{
$project: 
{
  individual: {
    $sum: '$dailyNotes.individual'
  }
}
}

谁能解释一下为什么它返回0而不是265,以及如何解决这个问题?

[Update]: (example with multiple(max 3) records)个 对于像这样的文档:

{
   "_id":"2023-04-08",
   "dailyNotes":[
      {
         "therapyDiscipline":"PT",
         "individual":[
            60,
            45,
            30,
            75,
            55
         ]
      },
      {
         "therapyDiscipline":"YT",
         "individual":[
            2,
            4
         ]
      }
   ]
}

它应该返回为:

{
   "_id":"2023-04-08",
   "dailyNotes":[
      {
         "individual":265
      },
      {
         "individual":6
      }
   ]
}

推荐答案

要做到这一点,最简单的方法是使用$map$sum

db.collection.aggregate([
  {
    $project: {
      _id: 1,
      dailyNotes: {
        $map: {
          input: "$dailyNotes",
          in: { individual: { $sum: "$$this.individual" } }
        }
      }
    }
  }
])

playground

一种使用$reduce的替代方案

db.collection.aggregate([
  {
    $project: {
      _id: 1,
      dailyNotes: {
        $reduce: {
          input: "$dailyNotes",
          initialValue: [],
          in: { $concatArrays: [ "$$value", [ { individual: { $sum: "$$this.individual" } } ] ] }
        }
      }
    }
  }
])

playground

Javascript相关问答推荐

Flutter:显示PDF和视频,但阻止下载

如何让\w token 在此RegEx中表现得不贪婪?

积分计算和 colored颜色 判断错误

为什么我达到了时间限制!?LeetCode链接列表循环(已解决,但需要解释!)

如何使用JavaScript用等效的功能性HTML替换标记URL格式?

微软Edge编辑和重新发送未显示""

有没有可能使滑动img动画以更快的速度连续?

v—自动完成不显示 Select 列表中的所有项目

如何从Intl.DateTimeFormat中仅获取时区名称?

这个值总是返回未定义的-Reaction

在HTML语言中调用外部JavaScript文件中的函数

以Angular 实现ng-Circle-Progress时出错:模块没有导出的成员

用于在路径之间移动图像的查询

邮箱密码重置链接不适用于已部署的React应用程序

面对代码中的错误作为前端与后端的集成

如何使用基于promise (非事件emits 器)的方法来传输数据?

为什么延迟在我的laravel项目中不起作用?

在查看网页时,如何使HTML中的按钮工作方式类似于鼠标上的滚轮或箭头键?

将Auth0用户对象存储在nextjs类型脚本的Reaction上下文中

如何在AG-Grid文本字段中创建占位符