如何在 mongodb 聚合中填充 objectIds 数组?

时间:2021-02-10 21:31:00

标签: mongodb populate

遇到问题。

我有标签架构和课程架构。 课程有一组标签架构的 ObjectId。

如何使用完整的架构详细信息填充这些标签。

Sample Tag Object
{
   _id: 44ffbvb...,
   title: "Tag 1
}

示例课程对象

_id: 44ffaab23231,
tags: [ObjectId(44ffbvb...),..]

如何在使用管道时填充那些在聚合中执行 $lookup 阶段的标签字段?

1 个答案:

答案 0 :(得分:1)


// Tag: collection name `tags`
[
  {
    _id: ObjectId("44ffbvb..."),
    title: "Tag 1"
  }
]

// Course: collection name `courses`
[
  {
    _id: ObjectId("44ffaab23231"),
    tags: [
      ObjectId("44ffbvb..."),
      ObjectId("44ffbvc..."),
      ObjectId("44ffbvd...")
    ]
  }
]

// Query using aggregate pipeline
db.courses.aggregate([
  {
    $match: {
      "name": "MongoDB"
    }
  },
  {
    $lookup: {
      from: "tags",
      let: { tags: "$tags" },
      pipeline: [
        {
          $match: {
            $expr: { $in: ["$_id", "$$tags"] }
          }
        },
        {
          $project: {
            "title": 1
          }
        }
      ],
      as: "tags"
    }
  }
])
相关问题