hades
hades

Reputation: 4696

Copy array to another array in same collection

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.

Upvotes: 0

Views: 26

Answers (1)

nimrod serok
nimrod serok

Reputation: 16033

One option is:

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

See how it works on the playground example

Upvotes: 1

Related Questions