• Post author:
  • Post category:MongoDB
  • Post last modified:May 9, 2024
  • Reading time:9 mins read
You are currently viewing MongoDB $elemMatch Operator Usage

In MongoDB, the $elemMatch operator is used to query documents that contain arrays and retrieve only the elements within the array that match specific conditions. The $elemMatch operator makes exact querying and retrieval of individual array items that satisfy the stated criteria possible, which is very helpful when working with complex conditions within arrays.

Advertisements

We will discuss the $elemMatch operator of MongoDB in this specific article. First, let’s create and insert a few documents into the student collection.


# Create Collection
db.student.insertMany([
{
   "_id" : 1,
   "details" : [
      {"name": "Jennah", "age" : 23}
   ],
  "marks": [80, 89, 90]
},
{
   "_id" : 2,
   "details" : [
      { "name": "Emily", "age" : 21 }
   ],
  "marks": [90, 85, 70]
},
{ "_id" : 3, 
  "details" : [
      { "name": "Sam", "age" : 25 }
   ],
 "marks": [86, 79, 70]
} ,
{
   "_id" : 4,
   "details" : [
      { "name": "Alex", "age" : 22}
   ],
 "marks": [88, 81, 78] 
}
])

1. Syntax of $elemMatch operator

The elemMatch operator syntax in MongoDB follows the pattern:


# Syntax of $elemMatch operator
db.find({ field: { $elemMatch: { condition } } })

In this case, the field signifies the array field on which the query will be run, and the condition specifies the criteria that the array element or elements must satisfy for the document to be included in the result set.

2. Using the $elemMatch operator in MongoDB

The usage of the $elemMatch operator is explained with the following query, which sets the criteria of the array elements.


# $elemMatch operator with find method
db.student.find({
    "marks": {
        $elemMatch: {
            $lt: 80
        }
    }
});

The query specified above finds the documents in the student collection where the marks field contains at least one element that is less than 80. Here, we provide the $elemMatch operator to the marks that match documents that contain an element in the marks array that satisfies the specified condition. The $elemMatch operator inputs the $lt operator which checks if any element in the marks array is less than 80.

Hence, the documents from the student collection whose marks match the criteria is displayed in the output.

elemMatch operator in MongoDB

3. Using the $elemMatch operator with multiple conditions

However, the $elemMatch operator also passed multiple criteria at the same time. The following is a query where the logical operators are set in the $elemMatch operator.


# Usage of $elemMatch operator with multiple conditions
db.student.find(
   { "marks": { $elemMatch: { $gte: 80, $lt: 85 } } }
)

The query specified above searches the documents in the student collection where the marks field contains at least one element that is greater than or equal to 80 and less than 85. The $elemMatch operator is used here to match the document according to the conditions passed to it. We passed the $gte and $lt operators at the same time in the $elemMatch operator. The $gte operator checks if any element in the marks array is greater than or equal to 80. On the other hand, the $lt operator checks if any element in the marks array is less than 85.

As a result, the documents are retrieved below, which have marks greater than or equal to 80 and less than 85.

4. Using the $elemMatch operator for embedded fields

The $elemMatch operator is applied for the array fields in the prior examples. However, the $elemMatch operator can also be used for matching the embedded fields in MongoDB.


# Usage of $elemMatch operator for embedded fields
db.student.find(
   { details: { $elemMatch: { name: "Alex", "age": { $gte: 22 } } } }
)

The query above finds documents in the student collection where the details field contains at least one subdocument that has the name Alex and an age greater than or equal to 22. We called the $elemMatch operator to match the documents that contain an element in the details array that fulfills the specified conditions. The conditions first validate if the embedded document within details has the name Alex. It also validates if the subdocument within details has an age greater than or equal to 22.

Thus, the documents which satisfied the criteria for embedded fields are yielded below.

elemMatch operator in MongoDB

5. Using the multiple $elemMatch operator in MongoDB

Moreover, the $elemMatch operator can also be utilized more than one time in a specific query to match the elements. The multiple $elemMatch operator query is explained below.

The query is defined with the logical operator $or for multiple conditions evaluations. In this case, we searched for documents where the details field contains at least one subdocument that satisfies either of the two specified conditions. Each condition uses the $elemMatch operator to match subdocuments within the details array that meets the specified criteria. The first condition searches for the subdocument with the name Emily and age 21, while the second condition searches for the subdocument with the name Sam and age 25.


# Usage of multiple $elemMatch operator
db.student.find({
    $or: [
         {details: {$elemMatch: {"name": "Emily", "age": 21} } },
         {details: {$elemMatch: {"name": "Sam", "age": 25} } }
    ]
});

The output represents the documents retrieved after executing the above query.

elemMatch operator in MongoDB

6. Conclusion

In conclusion, the $elemMatch operator provides a simplified and efficient approach to filter and retrieve specific array elements. The $elemMatch operator is deeply explained here with the syntax and some examples executed on the MongoDB shell. 

More details about this method can be found here.