0
0
MongodbHow-ToBeginner · 4 min read

How to Use arrayFilters in MongoDB for Targeted Array Updates

In MongoDB, arrayFilters lets you specify which elements in an array to update when using update operations like updateOne or updateMany. You provide conditions inside arrayFilters to target array elements, and then use placeholders in the update query to apply changes only to those elements.
📐

Syntax

The arrayFilters option is used with update commands to specify conditions on array elements that should be updated. It works with update operators like $set, $inc, etc., and uses identifiers to refer to array elements.

Basic syntax:

db.collection.updateOne(
  {  },
  {  },
  { arrayFilters: [ { : {  } } ] }
)

Explanation:

  • <filter>: Selects the document(s) to update.
  • <update>: The update operation using placeholders like array.$[identifier].
  • arrayFilters: An array of filter objects defining conditions for array elements.
  • identifier: A variable name used in the update to refer to matching array elements.
mongodb
db.collection.updateOne(
  { _id: 1 },
  { $set: { "array.$[elem].field": "newValue" } },
  { arrayFilters: [ { "elem.conditionField": { $gt: 5 } } ] }
)
💻

Example

This example updates the score field to 100 for all array elements where the score is less than 50 in the document with _id: 1.

mongodb
db.students.insertOne({
  _id: 1,
  name: "Alice",
  scores: [
    { subject: "math", score: 45 },
    { subject: "english", score: 75 },
    { subject: "science", score: 30 }
  ]
})

// Update scores less than 50 to 100

db.students.updateOne(
  { _id: 1 },
  { $set: { "scores.$[elem].score": 100 } },
  { arrayFilters: [ { "elem.score": { $lt: 50 } } ] }
)

// Query to see updated document
db.students.find({ _id: 1 }).pretty()
Output
{ "_id" : 1, "name" : "Alice", "scores" : [ { "subject" : "math", "score" : 100 }, { "subject" : "english", "score" : 75 }, { "subject" : "science", "score" : 100 } ] }
⚠️

Common Pitfalls

Common mistakes when using arrayFilters include:

  • Not using the correct identifier in both the update and the arrayFilters array.
  • Forgetting to include arrayFilters option when using placeholders like $[elem], which causes errors.
  • Using conditions that do not match any array elements, resulting in no updates.
  • Trying to update nested arrays without proper filters.

Example of a wrong update missing arrayFilters:

mongodb
db.students.updateOne(
  { _id: 1 },
  { $set: { "scores.$[elem].score": 100 } }
  // Missing arrayFilters option here
)
Output
MongoError: The array filter for identifier 'elem' was not provided.
📊

Quick Reference

FeatureDescriptionExample
arrayFiltersFilters to select array elements to update[ { "elem.score": { $lt: 50 } } ]
Update placeholderUse in update to refer to filtered elements"scores.$[elem].score"
Update operatorsOperators like $set, $inc work with arrayFilters$set: { "scores.$[elem].score": 100 }
Multiple filtersYou can use multiple filters with different identifiers[ { "elem1.field": 1 }, { "elem2.field": 2 } ]
Error if missingUsing placeholders without arrayFilters causes errorsMongoError: The array filter for identifier 'elem' was not provided.

Key Takeaways

Use arrayFilters to target specific elements in arrays during updates.
Always match the identifier in the update query with the one in arrayFilters.
Forget to include arrayFilters causes errors when using placeholders like $[elem].
You can use multiple filters to update different array elements in one operation.
Test your filter conditions to ensure they match the intended array elements.