收藏
回答

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

数据库数据

{ "_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 个回答

  • Charb
    Charb
    2020-12-26
    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()
    
    



    2020-12-26
    有用 1
    回复
登录 后发表内容
问题标签