刚看了下sum的参数是Expression表达式,所以写出来了,不知道还有没有更简便的方法db.collection('taskToUser').aggregate() .unwind('$userList') .group({ _id: '$userList.userId', sum: $.sum(1), sumTrue: $.sum( $.cond({ if: $.eq(['$userList.isCompeted', true]), then: 1, else: 0 }) ), sumFalse: $.sum( $.cond({ if: $.eq(['$userList.isCompeted', false]), then: 1, else: 0 }) ), }) .sort({ sumTrue: -1 }) .end()
云开发数据库sum统计,如何根据字段判断sum是否计数?查询语句: db.collection('taskToUser').aggregate() .unwind('$userList') .group({ _id: '$userList.userId', sum: $.sum(1), sumTrue: $.sum(1), sumFalse: $.sum(1), }) .end() 查询结果: [ { "_id": "ovXd05X4Dep9Z6Y2siKO1YKZOd8E", "sum": 27, "sumTrue": 27, "sumFalse": 27 }, { "_id": "ovXd05RxUd-W39WyGbAdca7XwKfE", "sum": 27, "sumTrue": 27, "sumFalse": 27 }, { "_id": "ovXd05WQOtTLR_IPYs6_UTq2NNDE", "sum": 91, "sumTrue": 91, "sumFalse": 91 } ] 我想让sum1字段和sum2字段,根据数据的一个字段(bool类型的)来判断是否计数,结果类似这样:sum=sumTrue+sumFalse { "_id": "ovXd05WQOtTLR_IPYs6_UTq2NNDE", "sum": 91, "sumTrue": 40, "sumFalse": 51 }
2022-01-15