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

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay