MongoDB聚合查询如何过滤lookup关联结果为空数组的文档
解决方案
你只需要在现有聚合管道的$lookup阶段之后,新增一个$match阶段过滤掉profileId为空数组的文档即可,修改后的完整代码如下:
User.aggregate( [ { $match: { _id: { $ne: req.user.id }, isDogSitter: { $eq: true }, profileId: { $exists: true } }}, { $project: { firstName: 1, lastName: 1, email: 1, isDogSitter: 1, profileId: 1, }}, { $lookup: { from: "profiles", pipeline: [ { $project: { __v: 0, availableDays: 0, }}, { $match: { city: search }} ], as: "profileId", }}, // 新增过滤阶段,排除profileId为空数组的文档 { $match: { profileId: { $ne: [] } } } ], (error, result) => { console.log("RESULT ", result); } );
上述代码中$ne: []会直接过滤掉所有没有匹配到对应profile的用户文档,当没有符合条件的关联数据时,最终返回的result就是空数组,完全符合你的需求。
内容的提问来源于stack exchange,提问作者Gurkiran Singh
相关产品推荐
相关产品推荐

