MongoDB Replace specific array values

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

Leave a Comment