使用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], " leftVoted" :[1,6]}
{" _id" :ObjectId(" 5a2c0d68efde3416bc8b7020")," rightVoted" :[2], " leftVoted" :[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
为votesCount = 3
。我希望用户1为votesCount = 2
,用户2为{{1}}。
答案 0 :(得分:3)
$leftVotesCount
,$rightVotesCount
仅在下一阶段可用。尝试类似:
User.aggregate()
.project({
'_id': 1,
'leftVotesCount': { '$size': '$leftVoted' },
'rightVotesCount': { '$size': '$rightVoted' }
})
.project({
'_id': 1,
'leftVotesCount': 1,
'rightVotesCount': 1
'votesCount': { '$add': [ '$leftVotesCount', '$rightVotesCount' ] },
'votesCount2': { '$sum': [ '$leftVotesCount', '$rightVotesCount' ] }
})
答案 1 :(得分:2)
您无法参考在同一项目阶段创建的项目变量。
您可以将变量包装在$let
表达式中。
User.aggregate().project({
"$let": {
"vars": {
"leftVotesCount": {
"$size": "$leftVoted"
},
"rightVotesCount": {
"$size": "$rightVoted"
}
},
"in": {
"votesCount": {
"$add": [
"$$leftVotesCount",
"$$rightVotesCount"
]
},
"leftVotesCount": "$$leftVotesCount",
"rightVotesCount": "$$rightVotesCount"
}
}
})
答案 2 :(得分:1)
事实证明$add
支持嵌套表达式,所以我能够通过排除中间变量来解决问题:
User.aggregate().project({
'_id': 1,
'votesCount': { '$add': [ { '$size': '$leftVoted' }, { '$size': '$rightVoted' } ] }
});
// [ {_id: '...', votesCount: 3}, {_id: '...', votesCount: 2} ]