0

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.

Sssssuppp
  • 683
  • 1
  • 7
  • 29

1 Answers1

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

mongoplayground

YuTing
  • 6,555
  • 2
  • 6
  • 16
  • This is what im looking for. Another related question -- is it possible to replace "$currentNumber" with another integer which I have defined in nodeJS, say ```const randomNumber``` – Sssssuppp Feb 19 '22 at 12:30
  • 1
    @Satya Sure you can. Change `[ "$currentNumber" ]` into `[ randomNumber ]` – YuTing Feb 19 '22 at 13:24
  • Finally, can I replace the expression in such a way that ```$currentNumber``` is greater than some ```lowerLimit```? – Sssssuppp Feb 19 '22 at 13:33
  • 1
    @Satya change `$eq: [ { $mod: [ "$currentNumber", 2 ] }, 1 ]` into `$gt:[ "$currentNumber", lowerLimit ]` – YuTing Feb 19 '22 at 13:49