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

如何修改MongoDB聚合查询合并users与user_relations两个集合的数据

解决方案

你可以在现有聚合管道的$replaceRoot阶段后新增关联和字段加工逻辑,完整查询代码如下:

db.user_relations.aggregate([
  {
    "$match": {
      "userId": "userId1"
    }
  },
  {
    "$unwind": {
      "path": "$friendsArray"
    }
  },
  {
    "$sort": {
      "friendsArray.lastTimestamp": 1
    }
  },
  {
    "$limit": 10
  },
  {
    "$replaceRoot": {
      "newRoot": "$friendsArray"
    }
  },
  # 以下为新增的关联和字段加工阶段
  {
    "$lookup": {
      "from": "users",
      # 注意:如果users集合的_id是ObjectId类型,此处需要改为 "localField": { "$toObjectId": "$userId" } 做类型转换
      "localField": "userId",
      "foreignField": "_id",
      "as": "userInfo"
    }
  },
  {
    "$unwind": "$userInfo"
  },
  {
    "$project": {
      "_id": 0,
      "userId": 1,
      "lastTimestamp": 1,
      "message": 1,
      "nameAndSurname": "$userInfo.nameAndSurname",
      "pictureUrl": { "$arrayElemAt": ["$userInfo.arrayOfImages", 0] }
    }
  }
])

补充说明

如果部分用户的arrayOfImages为空数组,pictureUrl会返回null,你可以根据业务需要新增$cond逻辑设置默认占位图地址。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 21:21:03