Sling Academy
Home/MongoDB/MongoDB: Using $elemMatch operator to match elements in an array

MongoDB: Using $elemMatch operator to match elements in an array

Last updated: February 03, 2024

Introduction

When working with MongoDB, one often comes across scenarios where it is necessary to query documents based on the elements within an array. MongoDB provides a powerful operator called $elemMatch which allows us to do precisely that. In this tutorial, we will explore the $elemMatch operator with a variety of code examples to help you understand and utilize its full potential.

Understanding the $elemMatch Operator

The $elemMatch operator is used within queries to specify a condition on elements of an array such that at least one element satisfies all the specified query criteria. This becomes particularly useful when the elements of an array are subdocuments or when we need to match more than one field within each element.

Basic Usage of $elemMatch

db.collection.find({
  arrayField: {
    $elemMatch: { key1: value1, key2: value2 }
  }
});

The above query will return documents where arrayField contains at least one element that has both key1 with value1 and key2 with value2.

Example: Filtering Based on a Single Condition

db.students.find({
  scores: {
    $elemMatch: { score: { $gte: 70 } }
  }
});

This query will retrieve all documents from the students collection where the scores array contains at least one score that is greater than or equal to 70. The output might appear as follows:

[{
  _id: ObjectId('...'),
  name: "John Doe",
  scores: [{ score: 80 }, { score: 90 }, ...]
}, ...]

Example: Combining Conditions on Array Elements

db.students.find({
  courses: {
    $elemMatch: { name: "Mathematics", grade: { $gt: 'B' } }
  }
});

In this example, the query returns students who have a course named “Mathematics” with a grade strictly greater than ‘B’ in their courses array. Multiple fields are combined to narrow down the search.

Using $elemMatch with Projection

$elemMatch can also be used in the projection phase of a query to return only the specific matching array elements:

db.students.find(
  {},
  { scores: { $elemMatch: { score: { $gte: 70 } } } }
);

This query returns all student documents but includes only the first scores array element with a score of at least 70.

Advanced Usage of $elemMatch

Nested Array Matching

In cases where the arrays are nested within other arrays, $elemMatch becomes essential to pinpoint the exact depth of the element you’re searching for.

db.classes.find({
  'students.scores': {
    $elemMatch: {
      $elemMatch: { score: { $gte: 85 } }
    }
  }
});

This advanced usage allows you to query for classes where there is a student with a nested scores array containing a score of 85 or higher.

Combining $elemMatch with Other Operators

$elemMatch can be combined with other operators to create complex queries. For instance, using it with $not to exclude certain elements.

db.orders.find({
  items: {
    $elemMatch: { item: "journal", qty: { $not: { $lte: 50 } } }
  }
});

This query searches for orders containing an item of the type “journal” where the quantity is not less than or equal to 50.

Conclusion

MongoDB’s $elemMatch operator is an essential tool for querying arrays, especially when the elements are complex or need to satisfy multiple conditions. The flexibility and power of the operator can be leveraged to write precise queries which is crucial for efficient database operations. Through the examples provided, you should now have a good grounding in how to apply $elemMatch in various scenarios for your MongoDB queries.

Next Article: Matching binary values in MongoDB: A practical guide (with examples)

Previous Article: MongoDB: using $all operator to match arrays (with examples)

Series: MongoDB Tutorials

MongoDB

You May Also Like

  • MongoDB: How to combine data from 2 collections into one
  • Hashed Indexes in MongoDB: A Practical Guide
  • Partitioning and Sharding in MongoDB: A Practical Guide (with Examples)
  • Geospatial Indexes in MongoDB: How to Speed Up Geospatial Queries
  • Understanding Partial Indexes in MongoDB
  • Exploring Sparse Indexes in MongoDB (with Examples)
  • Using Wildcard Indexes in MongoDB: An In-Depth Guide
  • Matching binary values in MongoDB: A practical guide (with examples)
  • Understanding $slice operator in MongoDB (with examples)
  • Caching in MongoDB: A practical guide (with examples)
  • CannotReuseObject Error: Attempted illegal reuse of a Mongo object in the same process space
  • How to perform cascade deletion in MongoDB (with examples)
  • MongoDB: Using $not and $nor operators to negate a query
  • MongoDB: Find SUM/MIN/MAX/AVG of each group in a collection
  • References (Manual Linking) in MongoDB: A Developer’s Guide (with Examples)
  • MongoDB: How to see all fields in a collection (with examples)
  • Type checking in MongoDB: A practical guide (with examples)
  • How to query an array of subdocuments in MongoDB (with examples)
  • MongoDB: How to compare 2 documents (with examples)