Use the all positional operator in MongoDB to update all elements in an array
For a full overview of MongoDB and all my posts on it, check out my overview.
MongoDB provides a special update operator $[]
to apply an update operation to all elements in an array belonging to matching documents.
With the following data inserted into a collection called games
:
db.games.insertMany(
{
name: "Genshin Impact",
reviewScores: [8, 6, 9, 5]
},
{
name: "Factorio",
reviewScores: [7, 7, 10, 8]
},
{
name: "Bloodborne",
reviewScores: [9, 8, 9, 9]
}
)
For every game that does NOT have a score of 10 in its reviews, increase all the review scores by 1.
db.games.updateMany(
{ reviewScores: { $ne: 10 } },
{ $inc: { "reviewScores.$[]": 1 } }
)
Use the find method to read all the data back out to view the results:
{
name: "Genshin Impact",
reviewScores: [9, 7, 10, 6]
},
{
name: "Factorio",
reviewScores: [7, 7, 10, 8]
},
{
name: "Bloodborne",
reviewScores: [10, 9, 10, 10]
}
Related
Did you find this information useful? If so, consider heading over to my donation page and drop me some support.
Want to ask a question or just chat? Contact me here