Home > Enterprise >  Push contents of one field to another field (array) if condition is satisfied - MongoDB
Push contents of one field to another field (array) if condition is satisfied - MongoDB

Time:02-20

This is not what I'm looking for: Update MongoDB field using value of another field

I am trying to copy the contents of one field, into another field (which happens to be an array) if a condition evaluates to true.

Initial document state:

{
   _id: 1234
   currentNumber: 5
   magicNumbers: [3, 7, 9, 11, 15]
}

I want to copy contents of currentNumber to magicNumbers if currentNumber % 2 == 1. Is this possible in the latest MongoDB version? I'm using Nodejs driver.

Final document state:

{
   _id: 1234
   currentNumber: 5
   magicNumbers: [3, 7, 9, 11, 15, 5]
}

I want to do this in a single pass, to save trips to the database.

CodePudding user response:

db.collection.update({
  $expr: {
    $eq: [ { $mod: [ "$currentNumber", 2 ] }, 1 ]
  }
},
[
  {
    $set: {
      magicNumbers: {
        $concatArrays: [ "$magicNumbers", [ "$currentNumber" ] ]
      }
    }
  }
],
{
  "multi": true
})

mongoplayground

  • Related