云开发数据库 对象数组的某个属性求和?

发布于 7 年前作者 jiafang4281 次浏览最后编辑 7 年前来自 ask

数据库数据

{ "_id": 1, "name":"Tom", "list": [{"course":"eglish", "score":60},{"course":"math", "score":70} ] }
{ "_id": 2, "name":"Kat", "list": [{"course":"eglish", "score":100},{"course":"math", "score":70}  ] }

要求输出数据结果

{ "_id": 1, "name":"Tom", "total":130, "list": [{"course":"eglish", "score":60},{"course":"math", "score":70} ] }
{ "_id": 2, "name":"Kat", "total":170, "list": [{"course":"eglish", "score":100},{"course":"math", "score":70} ] }

怎么数组中对象的某个属性求和? reduce可以吗?

1 回复
duxiulan
duxiulan1 楼5 年前
db.collection('集合名').aggregate()
.group({
_id: {
_id: '$_id',
name: '$name',
list: '$list',
temp: '$list',
}
})
.unwind('$_id.temp')
.group({
_id: {
_id:"$_id._id",
name:"$_id.name",
list:"$_id.list",
},
total: $.sum("$_id.temp.score")
})
.end()