You need to enable JavaScript to run this app. MongoDB聚合查询如何过滤lookup关联结果为空数组的文档
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 04:12:02