【问题标题】:MongoDB aggregation to replace array of ObjectIds with actual documentsMongoDB 聚合用实际文档替换 ObjectIds 数组
【发布时间】:2020-06-27 17:33:30
【问题描述】:

假设我们有一个包含一个文档的 db.orders 文档集合:

{"_id": "5ef62e0c586c78491530e4d5", "items": [{ "description": "desc1", "parts": ["5ef62e0c586c78491530e4d7", "5ef62e0c586c78491530e4d8"] } ], "createdBy": "userId"}

[更正:items 字段现在是一个数组]

还有另一个包含两个部分文档的 db.parts 集合:

{"_id": "5ef62e0c586c78491530e4d7", "name": "part1" }
{"_id": "5ef62e0c586c78491530e4d8", "name": "part2" }

我想在第一个集合上构造一个聚合,用实际文档替换parts 数组中的ObjectId。结果应该是这样的:

{"_id": "5ef62e0c586c78491530e4d5", "items": [{ "description": "desc1", "parts":
  [
    {"_id": "5ef62e0c586c78491530e4d7", "name": "part1" },
    {"_id": "5ef62e0c586c78491530e4d8", "name": "part2" }
  ]
}], "createdBy": "userId"}

任何想法都将不胜感激!

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    您需要使用$lookup 运算符:

    db.orders.aggregate([
      {
        $lookup: {
          from: "parts",
          localField: "items.parts",
          foreignField: "_id",
          as: "parts"
        }
      },
      {
        $project: {
          createdBy: 1,
          items: {
            $map: {
              input: "$items",
              as: "item",
              in: {
                description: "$$item.description",
                parts: {
                  $filter: {
                    input: "$parts",
                    as: "part",
                    cond: {
                      $in: [ "$$part._id", "$$item.parts" ]
                    }
                  }
                }
              }
            }
          }
        }
      }
    ])
    

    MongoPlayground

    【讨论】:

    • 谢谢!我实际上在我的问题中犯了一个错误。 “items”字段应该是一个数组,如:{“_id”:“5ef62e0c586c78491530e4d5”,“items”:[{“description”:“desc1”,“parts”:[“5ef62e0c586c78491530e4d7”,5ef62e0c586c78491530e4d8]}],“createdBy ": "userId"} 进行查找时,它不会将项目保留为数组,并且我会丢失“描述”字段。
    • @ThomasSkyttegaardHansen 请再次检查,我已经更新了答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-14
    • 2016-10-14
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    相关资源
    最近更新 更多