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
Top comments (0)