Goggies
Goggies

Reputation: 33

MongoDB How to replace array item by index

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

Upvotes: 3

Views: 1119

Answers (1)

Mohammad Faisal
Mohammad Faisal

Reputation: 2412

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

Upvotes: 4

Related Questions