3

How would I replace a value at a specific index in an array using MongoDB?

Lets say a collection for movie reviews has a rating array with individual numbers and I wanted to replace one with a new rating using only Indexes

let array = [1, 5, 3, 7]

How do I replace 5 with 4? Once again only using Indexes

1
  • var i = array.indexOf(5); array[i] = 4; Commented Feb 15, 2020 at 7:10

1 Answer 1

4

Suppose, you have a document

{ 
    "_id" : 1, 
    "array" :  [1, 5, 3, 7]
}

then, you can update array value at specific index using dot operator i.e, array.<index> with $set operator

db.collection.update(
  { /*match query*/ },
  { $set: { "array.1": 4 } }  // array.index where index=0,1,2,...
)

The Updated Document becomes,

{ 
    "_id" : 1, 
    "array" :  [1, 4, 3, 7]
}

You need to concatenate the index in key. Try this

 { _id: editedObj.id }, // Match id. 
{ $set: { [`reviews.${index}`]: editedObj.reviews}})
Sign up to request clarification or add additional context in comments.

11 Comments

{ _id: editedObj.id }, // Match id. { $set: { "reviews.index": editedObj.reviews}}); I am using node.js, when i try doing that using a variable with my index value it gives me an error. Any idea what i'm doing wrong?
@Goggies I have updated my code, Try this and let me know if this works for you or not.
Got this error Cannot create field '${index}' in element {reviews: [ "test" ]}
Will you Please Show me your Code.
let updated = await Movie.updateOne( { _id: editedObj.id }, // Match id. { $set: { "reviews.${index}": editedObj.reviews}});
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.