DEV Community

Cover image for Use the all positional operator in MongoDB to update all elements in an array
Donald Feury
Donald Feury

Posted on • Originally published at donaldfeury.xyz on

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

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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]
}
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)