【问题标题】:Merge/Combine two object arrays from different fields合并/组合来自不同字段的两个对象数组
【发布时间】:2021-08-31 00:10:56
【问题描述】:

我有一个数组 in_cart,其中包含 product_id(s) 和 amount 中的各个项目购物车文件

"in_cart":[
  {
    "product_id":"12345",
    "amount":2
  }  
]

我想要做的是将 amount 字段插入details 数组中。 $lookup 运算符在 product_id 上完成,因此两个数组中的项目数量始终相同。

"details":[
  {
    "_id":"12345",
    "name":"test",
    "price":1110,
    // ...more data...
  }
]

【问题讨论】:

    标签: mongodb mongodb-query nosql aggregation-framework


    【解决方案1】:
    • $map 遍历 details 数组。
    • $filterin_cart 数组中过滤出与 details 数组中的当前项目具有相同 product_id 字段值的文档在 _id 字段
    • $arrayElemAt 获取过滤后数组的第一个元素(因为它总是只有一个元素)
    • $getField 仅获取过滤项目的 amount 属性
    db.collection.aggregate([
      {
        $set: {
          details: {
            $map: {
              input: "$details",
              in: {
                _id: "$$this._id",
                name: "$$this.name",
                price: "$$this.price",
                amount: {
                  $getField: {
                    field: "amount",
                    input: {
                      $arrayElemAt: [
                        {
                          $filter: {
                            input: "$in_cart",
                            as: "cart_item",
                            cond: {
                              $eq: [
                                "$$cart_item.product_id",
                                "$$this._id"
                              ]
                            }
                          }
                        },
                        0
                      ]
                    }
                  }
                }
              }
            }
          }
        }
      }
    ])
    

    Working example

    【讨论】:

      最近更新 更多