Intermediate MongoDB

Working with Arrays in MongoDB

Query and update arrays using $elemMatch, $all, $push, $pull, and positional operators.

7 min read Tutorial

Arrays in MongoDB

One of MongoDB's strengths is native support for arrays as field values. You can store lists of strings, numbers, or even nested documents directly within a document. MongoDB provides specialized operators for querying and updating arrays efficiently.

Querying Arrays

A simple equality check matches documents where the array contains the specified value:

// Find articles tagged with "mongodb"
db.articles.find({ tags: "mongodb" })

// $all - Array must contain ALL specified values
db.articles.find({
  tags: { $all: ["mongodb", "tutorial"] }
})

// $size - Match arrays with exactly N elements
db.articles.find({ tags: { $size: 3 } })

$elemMatch

When array elements are objects, use $elemMatch to ensure multiple conditions apply to the same element:

// Document structure:
// { scores: [{ subject: "math", grade: 85 }, { subject: "english", grade: 92 }] }

// Find students with a math score above 90
db.students.find({
  scores: {
    $elemMatch: { subject: "math", grade: { $gt: 90 } }
  }
})

// Without $elemMatch, conditions could match different elements
// This would match if ANY score > 90 AND ANY subject is "math"
db.students.find({
  "scores.subject": "math",
  "scores.grade": { $gt: 90 }
})

Adding Elements to Arrays

Use $push and $addToSet to add elements:

// $push - Add an element (allows duplicates)
db.articles.updateOne(
  { _id: articleId },
  { $push: { tags: "featured" } }
)

// $addToSet - Add only if not already present
db.articles.updateOne(
  { _id: articleId },
  { $addToSet: { tags: "featured" } }
)

// $push with $each - Add multiple elements
db.articles.updateOne(
  { _id: articleId },
  { $push: { tags: { $each: ["new", "trending"] } } }
)

// $push with $sort and $slice - Maintain a sorted, capped array
db.users.updateOne(
  { _id: userId },
  {
    $push: {
      recentScores: {
        $each: [{ value: 95, date: new Date() }],
        $sort: { date: -1 },
        $slice: 10
      }
    }
  }
)

Removing Elements from Arrays

Use $pull and $pop to remove elements:

// $pull - Remove all matching elements
db.articles.updateOne(
  { _id: articleId },
  { $pull: { tags: "deprecated" } }
)

// $pull with conditions on array of objects
db.students.updateOne(
  { _id: studentId },
  { $pull: { scores: { grade: { $lt: 50 } } } }
)

// $pop - Remove first (-1) or last (1) element
db.queue.updateOne(
  { _id: queueId },
  { $pop: { items: -1 } }  // remove first element
)

Positional Operator ($)

The positional operator $ updates the first array element that matches the query:

// Update the grade of the matched "math" score
db.students.updateOne(
  { _id: studentId, "scores.subject": "math" },
  { $set: { "scores.$.grade": 95 } }
)

// $[] updates ALL elements in the array
db.students.updateOne(
  { _id: studentId },
  { $inc: { "scores.$[].grade": 5 } }
)

Key Takeaways

  • Use $elemMatch to match multiple conditions on the same array element.
  • $push adds elements; $addToSet prevents duplicates.
  • $pull removes by condition; $pop removes by position.
  • The positional operator $ targets the first matched array element.

Try this query in UnifySQL

Write, optimize, and collaborate on MongoDB queries with AI assistance.

Start Free