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

MongoDB中根据friends集合匹配为users集合添加friendStatus字段

我来帮你搞定这个MongoDB的数据关联需求~

解决方案

你可以借助MongoDB的聚合框架实现这个需求,具体的聚合查询代码如下:

// 先定义当前登录用户的ID
const currentUserId = ObjectId("5afaab572c4ec049aeb0bcba");

db.users.aggregate([
  // 关联friends集合,筛选出当前用户与目标用户的好友关系记录
  {
    $lookup: {
      from: "friends",
      let: { targetUserId: "$_id" },
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                // 好友记录必须同时包含当前登录用户和目标用户
                { $in: [currentUserId, ["$requester", "$recipient"]] },
                { $in: ["$$targetUserId", ["$requester", "$recipient"]] }
              ]
            }
          }
        },
        { $project: { status: 1, _id: 0 } } // 只保留status字段
      ],
      as: "tempFriendStatus"
    }
  },
  // 生成最终的friendStatus字段
  {
    $addFields: {
      friendStatus: {
        $cond: {
          if: { $gt: [{ $size: "$tempFriendStatus" }, 0] },
          then: { $arrayElemAt: ["$tempFriendStatus.status", 0] },
          else: 0 // 无匹配记录时设为0
        }
      }
    }
  },
  // 清理临时字段,让返回结果更整洁
  { $unset: "tempFriendStatus" }
])

代码逻辑说明

  • $lookup阶段:使用带自定义管道的关联方式,精准筛选出同时涉及当前登录用户和目标用户的好友记录,避免无效数据关联,最后只保留需要的status字段存到临时数组中。
  • $addFields阶段:通过条件判断处理临时数组:如果数组长度大于0,说明存在有效好友关系,取第一个记录的status值;否则直接设为0,赋值给friendStatus字段。
  • $unset阶段:移除临时生成的tempFriendStatus字段,保证返回的文档结构符合预期。

执行这段查询后,就能得到你想要的输出结果啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:17:02