DEV Community

Braincuber Technologies
Braincuber Technologies

Posted on

Use the filter MongoDB positional operator nested array

MongoDB provides a filter positional operator $[] 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]
}
)

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

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

{
name: "Genshin Impact",
reviewScores: [9, 7, 9, 6]
},
{
name: "Factorio",
reviewScores: [7, 7, 10, 8]
},
{
name: "Bloodborne",
reviewScores: [9, 8, 9, 9]
}

share this MongoDB positional operator nested array guide and follow for more informational content

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay