我的文档如下所示:
{
"_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
}
]
}