MongoDB聚合和嵌套数字数组
Posted
技术标签:
【中文标题】MongoDB聚合和嵌套数字数组【英文标题】:MongoDB Aggregate sum nested number array 【发布时间】: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。我做错了什么?
【问题讨论】:
【参考方案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
【讨论】:
以上是关于MongoDB聚合和嵌套数字数组的主要内容,如果未能解决你的问题,请参考以下文章