如何将 MongoDB 文档字段移动到对象数组?

How to move MongoDB document fields to an array of objects?

给定一组类似于以下文档的文档

{
    "_id": {
        "$oid": "60582f08bf1d636f4b762ebc"
    }
    "experience": [{
        "title": "Senior Customer Success Account Manager",
        "company": "Microsoft",
        "tenure": 8
    }, {
        "title": "Senior Service Delivery Manager",
        "company": "Microsoft",
        "tenure": 34
    }],
    "company3": "Oracle",
    "tenure3": 10,
    "title3": "Senior Customer Success Manager - EMEA |Oracle Marketing Cloud"
}

我如何编写 updateMany 或其他 shell 命令以将 company3、tenure3 和 title3 作为新对象移动到体验数组中 {company: <company3 value>, title: <title3 value>, tenure: <tenure3 value>}

您似乎正在寻找此汇总更新:

db.collection.update({},
[
  {
    $set: {
      experience: {
        $concatArrays: [
          "$experience",
          [
            {
              company: "$company3",
              title: "$title3",
              tenure: "$tenure3"
            }
          ]
        ]
      }
    }
  },
  {
    $unset: "company3"
  },
  {
    $unset: "tenure3"
  },
  {
    $unset: "title3"
  }
],
{
  multi: true
})

游乐场:https://mongoplayground.net/p/xoEveE0rdBN