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

问题描述

遇到问题。

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

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

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

示例课程对象

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

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

解决方法


// 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"
    }
  }
])

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...