3

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 ?

2 Answers 2

7

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}})
Sign up to request clarification or add additional context in comments.

Comments

1

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,
       },
     }
   );

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.