【发布时间】:2020-05-09 20:21:02
【问题描述】:
在多个阶段存在聚合和查找问题。问题是我无法匹配 userId 在最后一次查找中。如果我省略 { $eq: ['$userId', '$$userId'] } 它可以工作并符合其他标准。但不是userid。
我已经尝试添加池作为 let 并在最后阶段将其用作 { $eq: ['$userId', '$$pools.userId'] },但这也不起作用。我得到一个空的优惠券数组。
我通过以下查询得到了这个。我想我需要以某种方式使用$unwind?但还没有开始工作。有什么指点吗?
总共要加入三个集合。首先是 userModel,它应该包含池,然后池应该包含用户优惠券。
{
"userId": "5df344a1372f345308dac12a", // Match this usedId with below userId coming from the coupon
"pools": [
{
"_id": "5e1ebbc6cffd4b042fc081ab",
"eventId": "id999",
"eventStartTime": "some date",
"trackName": "tracky",
"type": "foo bar",
"coupon": []
}
]
},
我需要在优惠券数组中填充正确的数据(如下),其中包含匹配的 userId。
"coupon": [
{
"eventId": "id999",
"userId": "5df344a1372f345308dac12a", // This userId need to match the above one
"checked": true,
"pool": "a pool",
}
池项目:
const poolProject = {
eventId: 1,
eventStartTime: 1,
trackName: 1,
type: 1,
};
用户项目:
const userProjection = {
_id: {
$toString: '$_id',
},
paper: 1,
correctBetsLastWeek: 1,
correctBetsTotal: 1,
totalScore: 1,
role: 1,
};
聚合查询
const result = await userModel.aggregate([
{ $project: userProjection },
{
$match: {
$or: [{ role: 'User' },
{ role: 'SuperUser' }],
},
},
{ $addFields: { userId: { $toString: '$_id' } } },
{
$lookup: {
from: 'pools',
as: 'pools',
let: { eventId: '$eventId' },
pipeline: [
{ $project: poolProject },
{
$match: {
$expr: {
$in: ['$eventId', eventIds],
},
},
},
{
$lookup: {
from: 'coupons',
as: 'coupon',
let: { innerUserId: '$$userId' },
pipeline: [
{
$match: {
$expr: {
$eq: ['$userId', '$$innerUserId'],
},
},
},
],
},
},
],
},
},
]);
感谢您的任何意见!
编辑:
如果我移动第二个查找(优惠券),使它们处于相同的“级别”,它可以工作,但我希望将它放在池中。如果我添加as: 'pools.coupon',在最后一次查找中它会覆盖查找的池数据。
【问题讨论】:
标签: mongodb mongoose aggregation-framework