2

我尝试将数组内的文档属性设置为大写。这是 mongodb 游乐场的链接https://mongoplayground.net/p/BTP_h3kqK_S

这是一个文档示例

  {
    "_id": ObjectId("5e786a078bc3b3333627341e"),
    "value": {
      "items": [
        {
          "itemName": "alpha305102992",
          "itemNumber": ""
        },
        {
          "itemName": "beta305102630",
          "itemNumber": "P5000"
        },
        {
          "itemName": "gamma305102633 ",
          "itemNumber": ""
        }
      ]
    }
  }

我尝试将“itemName”设置为大写。

我想要的结果是:

  {
    "_id": ObjectId("5e786a078bc3b3333627341e"),
    "value": {
      "items": [
        {
          "itemName": "ALPHA305102992",
          "itemNumber": ""
        },
        {
          "itemName": "BETA305102630",
          "itemNumber": "P5000"
        },
        {
          "itemName": "GAMMA305102633 ",
          "itemNumber": ""
        }
      ]
    }
  }
4

2 回答 2

0

演示 - https://mongoplayground.net/p/geb1MRHXNyk

使用update-documents-with-aggregation-pipeline

db.collection.update({},
[
  {
    $set: {
      value: {
        items: { // set item to loop only once
          $map: {
            input: "$value.items", // loop over items
            in: {
              $mergeObjects: [ // merge document
                "$$this",
                { itemName: { $toUpper: "$$this.itemName" } } // change individual itemName to upper
              ]
            }
          }
        }
      }
    }
  }
])

聚合演示 - https://mongoplayground.net/p/9wtSkyjC88c

使用您的游乐场链接进行演示 - https://mongoplayground.net/p/5J7Qz97gZoJ

使用游乐场链接更新演示 - https://mongoplayground.net/p/8LHEuMakpFF

于 2021-04-27T10:53:23.480 回答
0
  • $mapvalue.items迭代数组的循环
  • 使用转换itemName为大写$toUpper
  • $mergeObjects将当前对象与更新itemName的字段合并
db.collection.update({},
  [{
    $set: {
      "value.items": {
        $map: {
          input: "$value.items",
          in: {
            $mergeObjects: [
              "$$this",
              { itemName: { $toUpper: "$$this.itemName" } }
            ]
          }
        }
      }
    }
  }]
)

操场

于 2021-04-27T10:59:40.280 回答