DEV Community

Cover image for Use the filter positional operator in MongoDB to update specific array elements
Donald Feury
Donald Feury

Posted on • Originally published at donaldfeury.xyz on

Use the filter positional operator in MongoDB to update specific array elements

For a full overview of MongoDB and all my posts on it, check out my overview.


MongoDB provides a filter positional operator $[<name_of_filter>] to only update some elements in an array. If you want to update all the elements in the array, use the all positional operator in MongoDB to update all elements in an array.

You must define the filters to use in a property called arrayFilters.

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 the game Genshin Impact, increase all the reviews by 1 that are less than 9.

db.games.updateMany(
    { name: "Genshin Impact" },
    { $inc: { "reviewScores.$[reviews]": 1 } },
    { arrayFilters: [
        { "reviews": { $lt: 9 } }
    ]}
)

Enter fullscreen mode Exit fullscreen mode

Notice in the $inc update operator, we reference the array filter defined called reviews to tell MongoDB which elements to update.

Use the find method to read data back out of MongoDB to view the results:

{
    name: "Genshin Impact",
    reviewScores: [9, 7, 9, 6]
},
{
    name: "Factorio",
    reviewScores: [7, 7, 10, 8]
},
{
    name: "Bloodborne",
    reviewScores: [9, 8, 9, 9]
}
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

👋 Kindness is contagious

Please leave your appreciation by commenting on this post!

It takes one minute and is worth it for your career.

Get started

Thank you in advance!

Top comments (0)

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay