Mongoose:聚合查询中的筛选器选项

pcww981p  于 9个月前  发布在  Go
关注(0)|答案(1)|浏览(132)

我在过滤查询中的数据时遇到了问题。我原来的查询可以工作,但是如果我在管道线的末尾添加一个match语句(如果代码中的Base),我会得到0个结果。Base是users中的一个字段。

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();

字符串

nszi6y05

nszi6y051#

当我阅读并理解你的问题时,我认为这个解决方案应该对你有效:
你最后推送的匹配条件是{ $match: { "userData.base": { $eq: base } } },但是在小组和项目阶段之后,你没有任何对userData的访问权,所以你的条件应该是{ $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();

字符串

相关问题