How the arrayFilters Parameter Works in MongoDB

In MongoDB, when you update documents that contain arrays, you have the option of using the arrayFilters parameter.

The arrayFilters parameter allows you to specify an array of filter documents that determine which array elements to modify.

In the update document, use the $[<identifier>] filtered positional operator, which identifies the array elements that match the arrayFilters conditions for the update operation.

Syntax

The syntax goes like this:

{ <update operator>: { "<array>.$[<identifier>]" : value } },
{ arrayFilters: [ { <identifier>: <condition> } ] }

So for example, when used with the updateMany() method, it goes like this:

db.collection.updateMany(
   { <query conditions> },
   { <update operator>: { "<array>.$[<identifier>]" : value } },
   { arrayFilters: [ { <identifier>: <condition> } ] }
)

Example

Suppose we have a collection called players with the following documents:

{ "_id" : 1, "scores" : [ 1, 5, 17 ] }
{ "_id" : 2, "scores" : [ 8, 17, 18 ] }
{ "_id" : 3, "scores" : [ 15, 11, 8 ] }

We could use the arrayFilters parameter to update only those array elements that have a value higher than a certain amount.

Example:

db.players.updateMany(
   { scores: { $gte: 10 } },
   { $set: { "scores.$[e]" : 10 } },
   { arrayFilters: [ { "e": { $gte: 10 } } ] }
)

Result:

{ "acknowledged" : true, "matchedCount" : 3, "modifiedCount" : 3 }

The message tells us that three documents were matched and modified.

Here’s what the documents look like now.

db.players.find()

Result:

{ "_id" : 1, "scores" : [ 1, 5, 10 ] }
{ "_id" : 2, "scores" : [ 8, 10, 10 ] }
{ "_id" : 3, "scores" : [ 10, 10, 8 ] }

We can see that all values that were previously greater than or equal to 10 are now 10.

In this case, I used e as the <identifier>. Note that the <identifier> must begin with a lowercase letter and contain only alphanumeric characters.