In MongoDB, I have a movie collection that has an array of languages , e.g.languages: [0:USA, 1: German, 2: French, ...etc]
The array values are not in any particular order.
How can I now update an array value based on some specific value? Let's say I want to update all "French" and replace it with "Francais" for the entire collection. How can I do that?
You can use the updateOne() or updateMany() methods to add, update, or remove array elements based on the specified criteria. It is recommended to use the updateMany() method to update multiple arrays in a collection.
To remove an element, update, and use $pull in MongoDB. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.
Update Nested Arrays in Conjunction with $[] The $[<identifier>] filtered positional operator, in conjunction with the $[] all positional operator, can be used to update nested arrays. The following updates the values that are greater than or equal to 8 in the nested grades. questions array if the associated grades.
To update all the elements of an array, call the forEach() method on the array, passing it a function. The function gets called for each element in the array and allows us to update the array's values. Copied! const arr = ['zero', 'one', 'two']; arr.
Use the positional $
operator which identifies the element in the languages
array to update without explicitly specifying its position in the array i.e. instead of knowing the position in advance and updating the element as:
db.movies.updateMany( { "languages": "French" }, { "$set": { "languages.2": "Francais" } } )
you can just use the $
operator as:
db.movies.updateMany( { "languages": "French" }, { "$set": { "languages.$": "Francais" } } )
Alternatively using the aggregation pipeline for update operations:
db.movies.updateMany( { "languages": "French" }, [ { "$set": { "languages": { "$map": { "input": "$languages", "in": { "$cond": [ { "$eq": ["$$this", "French"] }, "Francais", "$$this" ] } } } } } ] )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With