2

Given a collection of documents similar to the following document

{
    "_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"
}

How would I write an updateMany or other shell command to move company3, tenure3 and title3 inside the experience array as a new object {company: <company3 value>, title: <title3 value>, tenure: <tenure3 value>} ?

prasad_
  • 12,755
  • 2
  • 24
  • 36
  • You would use an Aggregation update - this allows move the three fields (as an object) into the `experience` array. You can us the [$concatArrays](https://docs.mongodb.com/manual/reference/operator/aggregation/concatArrays/index.html) operator tp accomplish this. – prasad_ Mar 22 '21 at 06:44
  • 1
    @Alexandry Raduca, if **codemonkey** has answered your question and you found his answer helpful, please don't be shy to upvote him and accept with `green` check button below.. – AlexZeDim Mar 22 '21 at 07:11

1 Answers1

3

Seems like you're looking for this aggregation update:

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

Playground: https://mongoplayground.net/p/xoEveE0rdBN

codemonkey
  • 7,325
  • 5
  • 22
  • 36