MongoDB 聚合查找,将两个集合的输出推送到子对象中

MongoDB aggregation lookup, push output of both collections into sub objects

https://mongoplayground.net/p/xQp-y1iXUtZ

有 2 个合集:

  1. 简介
  2. 订阅者

查找后,外来集合以数组形式返回。由于该数组中只能有一个元素(一个子只能有一个配置文件),我们取第一个。

现在,我也想将“subs”集合“推送”到一个对象中。 “subs”中有很多字段。

这是我的:

[
  {
    "PROFILE0": {
      "_id": "1",
      "name": "gk"
    },
    "_id": "1",
    "f1": "f1",
    "f2": "f1",
    "f3": "f1",
    "f4": "f1",
    "username": "gk"
  },
  {
    "PROFILE0": {
      "_id": "1",
      "name": "gk"
    },
    "_id": "2",
    "f1": "f1",
    "f2": "f3",
    "f3": "f4",
    "f4": "f5",
    "username": "gk"
  }
]

这就是我要找的:

[
  {
    "PROFILE0": {
      "_id": "1",
      "name": "gk"
    },
    "SUBS": {
      "_id": "1",
      "f1": "f1",
      "f2": "f1",
      "f3": "f1",
      "f4": "f1",
      "username": "gk"
    }
  },
  {
    "PROFILE0": {
      "_id": "1",
      "name": "gk"
    },
    "SUBS": {
      "_id": "2",
      "f1": "f1",
      "f2": "f3",
      "f3": "f4",
      "f4": "f5",
      "username": "gk"
    }

  }
]

本质上“本地”集合的内容也作为一个对象。

您在查找前添加投影,

  • $project 创建字段 SUBS 并将 $$ROOT 设置为根文档的值
  • $lookup加入配置文件集合,将SUBS.username作为localField传递,并将PROFILE0设置为as值,我们不需要$unset舞台
  • $set和你一样
db.subs.aggregate([
  {
    $project: {
      _id: 0,
      SUBS: "$$ROOT"
    }
  },
  {
    $lookup: {
      from: "profile",
      localField: "SUBS.username",
      foreignField: "name",
      as: "PROFILE0"
    }
  },
  {
    $set: {
      "PROFILE0": { $arrayElemAt: ["$PROFILE0", 0] }
    }
  }
])

Playground