加入 mongodb 中的多个集合并保留所有字段

Join multiple collections in mongodb and keep all fields

我是 NoSQL 数据库的新手,对集合聚合有点困惑。这是我正在尝试做的事情:我有三个集合:productCollectiondetailsCollectionbrandCollection.
productCollection 具有以下字段:_idnamedetails
detailsCollection_idbrand
brandCollection_idname

这些集合还有其他领域,但这些是我最感兴趣的。正如您可能猜到的,productCollection 中的 details 是对 detailsCollection_id 的引用,而 detailsCollection 中的 brand 是对 _idbrandCollection 中。我需要的是收集产品及其品牌。所以,基本上,我需要加入这三个集合并从 productCollection 中提取 name 并从 brandCollection

中提取 name

到目前为止,我设法编写了这个脚本:

db.productCollection.aggregate([
   {
      $lookup: {
         from: "detailsCollection",
         localField: "details",   
         foreignField: "_id",  
         as: "det"
      }
   },
   
   {
      $replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$det", 0 ] }, "$$ROOT" ] } }
   },
   
   { $project: { "det": 0 } },
   
   {
       $lookup: {
           from: "brandCollection",
           localField: "brand",
           foreignField: "_id",
           as: "br"
       }
   },
   
   {
      $replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$br", 0 ] }, "$$ROOT" ] } }
   },
   
   { $project: { "br": 0 } }
])

它显示了所有三个系列的所有字段,但没有显示品牌名称。我想这可能是因为 name 字段出现在 productCollectionbrandCollection 中。其他字段都没问题。
因此,我的问题是:如何使 brandCollection 中的 name 也出现在结果中?也许我可以在此过程中将其重命名为以另一个名称显示?有没有更简单的方法来加入这三个集合?或者上面的脚本可以吗?

感谢您的帮助!

  • $lookupdetailsCollection 集合
  • $lookupbrandCollection 并传递 localField 作为品牌 ID
  • $arrayElemAtbrand 结果中获取第一个元素
  • 删除不再需要的 details 字段
db.productCollection.aggregate([
  {
    $lookup: {
      from: "detailsCollection",
      localField: "details",
      foreignField: "_id",
      as: "brand"
    }
  },
  {
    $lookup: {
      from: "brandCollection",
      localField: "brand.brand",
      foreignField: "_id",
      as: "brand"
    }
  },
  {
    $addFields: {
      brand: {
        $arrayElemAt: ["$brand.name", 0]
      },
      details: "$$REMOVE"
    }
  }
])

Playground