我有一个MongoDB查询,例如
// Get scoreboard of challenge
response.aggregate = await ScoreBoardModel.aggregate([
{ $match: { challenge_id: mongoose.Types.ObjectId(req.body.challenge_id) } },
{ $group: { _id: '$user_id', value: { $sum: '$value' } } },
]);
哪个输出像
[
{
"_id": "5b762887b6e3a91c60c01718",
"value": 4300
},
{
"_id": "5b8b41f10186400163d0df83",
"value": 6800
},
{
"_id": "5b762590b6e3a91c60c01713",
"value": 2023
}
]
但我想执行此查询,如下所示:
response.aggregate = await ScoreBoardModel.aggregate([
{ $match: { challenge_id: mongoose.Types.ObjectId(req.body.challenge_id) } },
{ $lookup: {
from: 'appusers',
let: { 'user_id': '$user_id' },
pipeline: [{ $match: { $expr: { $eq: [ '$_id', '$$user_id' ] } } },],
as: 'user'
} },
{ $group: { _id: '$user_id', value: { $sum: '$value' } } },
]);
我想在
$lookup
中添加appusers
以获得每个appusers
的详细信息。我怎么做?
最佳答案
应用 $first
阶段后,需要使用 $group
聚合运算符返回第一个文档。
ScoreBoardModel.aggregate([
{ "$match": { challenge_id: mongoose.Types.ObjectId(req.body.challenge_id) } },
{ "$lookup": {
"from": "appusers",
"let": { "user_id": "$user_id" },
"pipeline": [{ "$match": { "$expr": { "$eq": [ "$_id", "$$user_id" ] } } }],
"as": "user"
}},
{ "$group": {
"_id": "$user_id",
"value": { "$sum": "$value" },
"appusers": { "$first": "$user" },
}}
])