【问题标题】:How can I populate nested array objects in mongoDB or mongoose?如何在 mongoDB 或 mongoose 中填充嵌套数组对象?
【发布时间】:2022-11-10 01:17:45
【问题描述】:

我有一个 orders 集合,其中每个 order 具有以下形状:

  {
    "_id": "5252875356f64d6d28000001",
    "lineItems": [
      { productId: 'prod_007', quantity: 3 }, 
      { productId: 'prod_003', quantity: 2 }
    ]
    // other fields omitted
  }

我还有一个products 集合,其中每个product 都包含一个唯一的productId 字段。

如何使用来自products 集合的匹配product 填充每个lineItem.productId?谢谢! :)

【问题讨论】:

  • 您也可以发布您的架构吗?

标签: mongodb mongoose aggregation-framework


【解决方案1】:

我不知道您想要的确切输出,但我认为这就是您要寻找的:

这里的技巧是在聚合阶段使用$lookup

  • 首先$unwind 解构数组并可以将每个id 与另一个集合合并。
  • 然后是$lookup 本身。这就像 SQL 中的联接。它合并具有相同 ID 的所需对象。
  • 然后使用$mergeObjects 重新创建种群以从两个集合中获取属性。
  • 最后重新组合对象以再次获取数组。
db.orders.aggregate([
  {
    "$unwind": "$lineItems"
  },
  {
    "$lookup": {
      "from": "products",
      "localField": "lineItems.productId",
      "foreignField": "_id",
      "as": "result"
    }
  },
  {
    "$set": {
      "lineItems": {
        "$mergeObjects": [
          "$lineItems",
          {
            "$first": "$result"
          }
        ]
      }
    }
  },
  {
    "$group": {
      "_id": "$_id",
      "lineItems": {
        "$push": "$lineItems"
      }
    }
  }
])

示例here

使用此查询,您拥有相同的初始数据,但“填充”了来自其他集合的值。

【讨论】:

    猜你喜欢
    • 2019-09-23
    • 2021-05-23
    • 2017-10-03
    • 2015-03-26
    • 2017-01-01
    • 2016-10-12
    • 1970-01-01
    • 2020-06-07
    相关资源
    最近更新 更多