数据库数据
{ "_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可以吗?
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()