You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB聚合查询:匹配指定区域后返回用户全量关联区域数据

MongoDB 关联集合过滤解决方案

核心思路

先筛选出**关联课程中至少有一门匹配指定location_id**的用户,再返回这些用户的全部课程数据,而非仅保留匹配的课程条目。

方法1:单聚合管道完成查询

假设你的集合结构如下:

  • User集合:存储用户基础信息,示例结构:{ _id: ObjectId("xxx"), username: "小李" }
  • Course集合:存储课程信息,通过user_id关联用户,示例结构:{ _id: ObjectId("yyy"), user_id: ObjectId("xxx"), location_id: 7777, course_name: "Python入门" }

直接用聚合管道关联并过滤:

db.User.aggregate([
  // 关联当前用户的所有课程记录
  {
    $lookup: {
      from: "Course",
      localField: "_id",
      foreignField: "user_id",
      as: "courses"
    }
  },
  // 过滤出满足条件的用户:课程列表中至少有一门匹配目标location_id
  {
    $match: {
      $expr: {
        $gt: [
          {
            $size: {
              $filter: {
                input: "$courses",
                cond: { $in: ["$$this.location_id", [7777, 8888]] } // 传入需要匹配的location_id数组
              }
            }
          },
          0
        ]
      }
    }
  }
])

方法2:分步查询优化性能

如果Course集合数据量庞大,先缩小目标用户范围再关联,能有效提升查询效率:

// 第一步:先获取所有匹配location_id的课程对应的用户ID
const targetUserIds = db.Course.distinct("user_id", { location_id: { $in: [7777, 8888] } });

// 第二步:查询这些用户,并关联他们的全部课程
db.User.aggregate([
  { $match: { _id: { $in: targetUserIds } } },
  {
    $lookup: {
      from: "Course",
      localField: "_id",
      foreignField: "user_id",
      as: "courses"
    }
  }
])

注意事项

  • 如果你的关联字段不是user_id(比如User集合中存储的是course_ids数组),需要对应调整$lookup的localField和foreignField参数;
  • 可根据实际数据规模选择方案:用户量较小选方法1,课程量较大选方法2。

内容的提问来源于stack exchange,提问作者D Singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 21:03:24