使用MongoDB 3.4.10和mongoose 4.13.6,我可以在User模型上计算两个数组的大小:
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
。我期待用户1的votesCount = 3
和用户2的votesCount = 2
。
$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' ] }
})
您无法引用在同一项目阶段中创建的项目变量。
您可以将变量包装在$let
表达式中。
User.aggregate().project({
"$let": {
"vars": {
"leftVotesCount": {
"$size": "$leftVoted"
},
"rightVotesCount": {
"$size": "$rightVoted"
}
},
"in": {
"votesCount": {
"$add": [
"$$leftVotesCount",
"$$rightVotesCount"
]
},
"leftVotesCount": "$$leftVotesCount",
"rightVotesCount": "$$rightVotesCount"
}
}
})
原来$add
支持嵌套表达式,所以我能够通过排除中间变量来解决这个问题:
User.aggregate().project({
'_id': 1,
'votesCount': { '$add': [ { '$size': '$leftVoted' }, { '$size': '$rightVoted' } ] }
});
// [ {_id: '...', votesCount: 3}, {_id: '...', votesCount: 2} ]