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

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.

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

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