Mongoose:聚合查询中的过滤选项

问题描述 投票:0回答:1

我在过滤查询中的数据时遇到问题。我的原始查询有效,但如果我在管道末尾添加匹配语句(如果代码中为 Base),我会得到 0 结果。 Base是用户中的一个字段。

    const aggregationPipeline = [
    { $match: { endDate: { $gte: startDate }, display: true } },
    { $lookup: { from: "users", localField: "user", foreignField: "_id", as: "userData" } },
    { $unwind: "$userData" },
    {
        $group: {
            _id: "$userData.crewCode",
            base: { $first: "$userData.base" },
            rank: { $first: "$userData.rank" },
            rosters: { $push: "$rawData" }
        }
    },
    { $project: { _id: 1, base: 1, rank: 1, rosters: 1 } },
    { $sort: { rank: 1, _id: 1 } }
];

if (base) {
    aggregationPipeline.push({ $match: { "userData.base": { $eq: base } } });
}

const userSchedules = await Schedule.aggregate(aggregationPipeline).exec();
mongodb mongoose aggregate
1个回答
0
投票

当我阅读并理解您的问题时,我认为这个解决方案适合您

解决方案:

您最后推送的匹配条件是

{ $match: { "userData.base": { $eq: base } } }
,但在小组和项目阶段之后,您将无法访问用户数据,因此您的条件应该是
{ $match: { "base": { $eq: base } } }

 const aggregationPipeline = [
    { $match: { endDate: { $gte: startDate }, display: true } },
    { $lookup: { from: "users", localField: "user", foreignField: "_id", as: "userData" } },
    { $unwind: "$userData" },
    {
        $group: {
            _id: "$userData.crewCode",
            base: { $first: "$userData.base" },
            rank: { $first: "$userData.rank" },
            rosters: { $push: "$rawData" }
        }
    },
    { $project: { _id: 1, base: 1, rank: 1, rosters: 1 } },
    { $sort: { rank: 1, _id: 1 } }
];

if (base) {
    aggregationPipeline.push({ $match: { "base": { $eq: base } } });
}

const userSchedules = await Schedule.aggregate(aggregationPipeline).exec();
© www.soinside.com 2019 - 2024. All rights reserved.