【问题标题】:MongoDB - Copy field to another collectionMongoDB - 将字段复制到另一个集合
【发布时间】:2023-01-10 08:41:11
【问题描述】:

假设我有收藏orders

[
  {
     "id":"1",
     "items":{
        "itemId":"1000",
        "name":"Item 1",
        "status":"STATUS"
     }
  },
  {
     "id":"2",
     "items":{
        "itemId":"1000",
        "name":"Item 1",
        "status":"ANOTHER_STATUS"
     }
  }
]

我有另一个收藏 item_projections 这是

[
  {
     "id":"1",
     "itemId":"1000",
     "name":"Item 1",
     "orderId":"1"
  },
  {
     "id":"1",
     "itemId":"1000",
     "name":"Item 1",
     "orderId":"2"
  }
]

对于集合 orders 中的每一项,我想将字段 status 复制到与订单匹配的投影 iditemId 以具有

[
  {
     "id":"1",
     "itemId":"1000",
     "name":"Item 1",
     "orderId":"1",
     "status":"STATUS"
  },
  {
     "id":"1",
     "itemId":"1000",
     "name":"Item 1",
     "orderId":"2",
     "status":"ANOTHER_STATUS"
  }
]

是否可以使用聚合查找和合并管道来做到这一点?

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    解决方案 1

    1. $lookup - item_projections集合(键:orderId)加入orders集合(键:id)并返回orders数组字段,仅包含status字段的文档。

    2. $replaceRoot - 用新文档替换输入文档。

      2.1. $mergeObjects - 将根文档与 orders 的第一个文档合并。

    3. $unset - 删除orders 字段。

      db.item_projections.aggregate([
        {
          "$lookup": {
            "from": "orders",
            "localField": "orderId",
            "foreignField": "id",
            "pipeline": [
              {
                $project: {
                  status: "$items.status"
                }
              }
            ],
            "as": "orders"
          }
        },
        {
          $replaceRoot: {
            newRoot: {
              $mergeObjects: [
                "$$ROOT",
                {
                  $first: "$orders"
                }
              ]
            }
          }
        },
        {
          $unset: "orders"
        }
      ])
      

      Sample Mongo Playground (Solution 1)


      方案二

      或者你可以用$project替换第二和第三阶段。

      {
        $project: {
          "id": 1,
          "itemId": 1,
          "name": 1,
          "orderId": 1,
          "status": {
            $first: "$orders.status"
          }
        }
      }
      

      Sample Mongo Playground (Solution 2)

    【讨论】:

      猜你喜欢
      • 2013-03-28
      • 2021-06-14
      • 2019-04-15
      • 2020-12-25
      • 1970-01-01
      • 2014-09-04
      • 2021-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多