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>} ?

2
  • You would use an Aggregation update - this allows move the three fields (as an object) into the experience array. You can us the $concatArrays operator tp accomplish this. Commented Mar 22, 2021 at 6: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.. Commented Mar 22, 2021 at 7:11

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.