我有一个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。我怎么做?
$lookup
appusers
$first 应用 $group 阶段后,需要使用聚合运算符返回第一个文档。
$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" }, }} ])