Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Replace specific array values

Tags:

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?

like image 868
Marc_L Avatar asked Jan 31 '18 15:01

Marc_L


People also ask

How do you update an array element in MongoDB?

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.

How do I remove a specific element from an array in MongoDB?

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.

How do I change the nested array element in MongoDB?

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.

How do you update an array?

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.


1 Answers

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"                         ]                     }                 }             }         } }     ] ) 
like image 146
chridam Avatar answered Nov 11 '22 10:11

chridam