【发布时间】:2018-06-03 00:23:10
【问题描述】:
使用 MongoDB 3.4.10 和 mongoose 4.13.6,我可以计算用户模型上两个数组的大小:
User.aggregate()
.project({
'_id': 1,
'leftVotesCount': { '$size': '$leftVoted' },
'rightVotesCount': { '$size': '$rightVoted' }
})
我的用户在哪里(db.users.find())
{ "_id" : ObjectId("5a2b21e63023c6117085c240"), "rightVoted" : [ 2 ], “左投票”:[1, 6] }
{ "_id" : ObjectId("5a2c0d68efde3416bc8b7020"), "rightVoted" : [ 2 ], “左投票”:[1]}
我得到了预期的结果:
[ { _id: '5a2b21e63023c6117085c240', leftVotesCount: 2, rightVotesCount: 1 },
{ _id: '5a2c0d68efde3416bc8b7020', leftVotesCount: 1, rightVotesCount: 1 } ]
问题。如何获得leftVotesCount 和rightVotesCount 数据的累积值?我尝试了以下操作:
User.aggregate()
.project({
'_id': 1,
'leftVotesCount': { '$size': '$leftVoted' },
'rightVotesCount': { '$size': '$rightVoted' },
'votesCount': { '$add': [ '$leftVotesCount', '$rightVotesCount' ] },
'votesCount2': { '$sum': [ '$leftVotesCount', '$rightVotesCount' ] }
})
但votesCount 是null 和votesCount2 是0 对于两个用户。我期待用户 1 的 votesCount = 3 和用户 2 的 votesCount = 2。
【问题讨论】: