云开发数据库 对象数组的某个属性求和?
发布于 5 年前 作者 jiafang 4142 次浏览 来自 问答

数据库数据

{ "_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 回复
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()

回到顶部