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

MongoDB如何查询互相关注的成对文档(A关注B且B关注A)

查询followers集合中所有双向回关用户

集合规则说明

followers集合存储用户关注关系,字段定义如下:

  • _id:文档唯一标识
  • _f:发起关注的用户ID
  • _t:被关注的目标用户ID
  • 可选字段如createdAt存储关注行为发生时间

双向关注判定逻辑:若集合中同时存在A关注B(_f=A, _t=B)、B关注A(_f=B, _t=A)两条记录,则A、B为互关关系,两条记录都需要返回,最终提取_f字段即可拿到所有互关用户ID。

示例数据

以下两条记录同时存在时,代表ID为611531d23039d93be3bf2e2a和61bdd50570a6a12866e3297f的两个用户互关,查询需要同时返回这两条文档:

{
  _id: "62a0f3fb362c239460e8ee09",
  _f: "611531d23039d93be3bf2e2a",
  _t: "61bdd50570a6a12866e3297f",
  createdAt: "2022-06-08T19:03:35.246Z"
},
{
  _id: "62a0f3fb362c239460e8ee09",
  _f: "61bdd50570a6a12866e3297f",
  _t: "611531d23039d93be3bf2e2a",
  createdAt: "2022-06-08T19:03:35.246Z"
}

查询实现

通过MongoDB聚合管道自关联匹配反向关注记录,过滤出互关关系即可:

db.followers.aggregate([
  // 自关联匹配反向关注记录
  {
    $lookup: {
      from: "followers",
      let: { sourceUser: "$_f", targetUser: "$_t" },
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                { $eq: ["$_f", "$$targetUser"] },
                { $eq: ["$_t", "$$sourceUser"] }
              ]
            }
          }
        }
      ],
      as: "reverseRelation"
    }
  },
  // 过滤掉不存在反向关注的单关记录
  {
    $match: {
      reverseRelation: { $ne: [] }
    }
  },
  // 移除关联产生的临时字段
  {
    $project: {
      reverseRelation: 0
    }
  }
])

如果不需要返回完整文档,只需要去重后的所有互关用户ID列表,在上述管道末尾追加分组阶段即可:

{
  $group: {
    _id: null,
    mutualFollowUserIds: { $addToSet: "$_f" }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 21:21:36