0

I want to copy items from admin to newAdmins if it does not exist in the newAdmins

Before:

[
  {
    _id: "60801199bf57265ed8b786bc",
    admins: [
     "Kenny"
     "Abu"
     "Raj"
    ],
    newAdmins: [
     "Kenny"
     "Abu"
    ]
  }
]

After:

[
  {
    _id: "60801199bf57265ed8b786bc",
    admins: [
     "Kenny"
     "Abu"
     "Raj"
    ],
    newAdmins: [
     "Kenny"
     "Abu"
     "Raj"
    ]
  }
]

Searched online but could not find a simpler way to do it.

1 Answer 1

1

One option is:

db.collection.update({},
[
  {
    $set: {
      newAdmins: {
        $setUnion: [
          "$newAdmins",
          "$admins"
        ]
      }
    }
  }
], 
{multi: true})

See how it works on the playground example

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

4 Comments

i run it says fail to run update: update document must contain key beginning with '$'
Is it working for you on the playground example? Did you copy the $set part?
playground not working, ya it has the $set part, i just click on the playground example link and click run
You are right. It was my bad. Updated it now

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.