Jeanluca Scaljeri
Jeanluca Scaljeri

Reputation: 29109

mongodb: how to update array element by index number

Suppose you have documents like this:

{
    _id: 'sdsdfsd',
    a: [
          { x: 0, y: 0, z: 0 }
          { x: 0, y: 0, z: 0 }
          { x: 0, y: 0, z: 0 }
          { x: 0, y: 0, z: 0 }
    ]
}

So, if you have the _id and an index number (say: 2). Now, for that index I want to change the x value to 1. Is this possible in mongo or should I first retrieve the whole array, update the specific value and update the whole array by inserting it back ?

Upvotes: 3

Views: 4625

Answers (2)

Uptimist
Uptimist

Reputation: 21

Else you can go further, you can construct your way to the value with the variable indexes. Use string template

   yourModel.findOneAndUpdate(
     { _id: "sdsdfsd" },
     {
       $set: {
         [`a.${index}.x`]: newValue,
       },
     }
   );

Upvotes: 1

JohnnyHK
JohnnyHK

Reputation: 311855

You can access a specific array element in an update by its 0-based index using dot-notation:

// Set the x property of the third element of a to 1
db.test.update({_id: 'sdsdfsd'}, {$set: {'a.2.x': 1}})

Upvotes: 6

Related Questions