EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials MongoDB Tutorial MongoDB $elemMatch
Secondary Sidebar
MongoDB Tutorial
  • Commands
    • Mongodb updateMany
    • MongoDB Aggregation
    • Mongodb unwind
    • Mongodb where
    • MongoDB BSON
    • MongoDB Filter
    • Mongodb Match
    • MongoDB sort by date
    • MongoDB Limit()
    • MongoDB Atlas Login
    • MongoDB Relational Database
    • MongoDB count
    • MongoDB Aggregate
    • MongoDB Distinct
    • MongoDB Unique
    • MongoDB find
    • MongoDB findOne()
    • MongoDB insert
    • MongoDB Delete
    • MongoDB Update
    • Lookup in MongoDB
    • order by in MongoDB
    • MongoDB $regex
    • MongoDB $elemMatch
    • MongoDB ObjectId()
    • MongoDB Skip()
    • MongoDB findAndModify
    • Mongodb findOneAndUpdate
    • MongoDB Date Query
    • MongoDB Timestamp
    • MongoDB sort()
    • MongoDB group by
    • MongoDB Join
  • Basics
    • What is MongoDB
    • How To Install MongoDB
    • MongoDB Tools
    • MongoDB GUI Tools
    • MongoDB Versions
    • MongoDB Commands
    • Advantages of MongoDB
    • MongoDB Features
    • Is MongoDB NoSQL
    • Is MongoDB Open Source
    • Build Web Applications using MongoDB
    • MongoDB Data Types
    • MongoDB Administration
    • Data Modeling in MongoDB
    • MongoDB vs Elasticsearch
    • MariaDB vs MongoDB
    • Firebase vs MongoDB
  • Advanced
    • MongoDB Array
    • PostgreSQL ARRAY_AGG()
    • Indexes in MongoDB
    • MongoDB create Index
    • MongoDB Collection
    • MongoDB List Collections
    • MongoDB Capped Collections
    • MongoDB Delete Collection
    • Mongodb show collections
    • MongoDB Auto Increment
    • MongoDB Triggers
    • MongoDB Projection
    • Replication in MongoDB
    • MongoDB Database
    • Mongo DB Create Database
    • MongoDB Compass
    • MongoDB Users
    • MongoDB Authentication
    • MongoDB GridFS
    • MongoDB Relationships
    • MongoDB MapReduce
    • MongoDB Geospatial
    • MongoDB Monitoring
    • Backup in MongoDB
    • MongoDB Sharding
    • MongoDB Java Drivers
    • MongoDB Import
    • Mongo Database Interview Questions
    • MongoDB Join Two Collections
    • MongoDB Group by Multiple Fields
    • MongoDB Pagination
    • MongoDB Replica Set
    • MongoDB Bulk Update
    • MongoDB greater than
    • MongoDB Encryption
    • MongoDB find in array
    • MongoDB like query
    • Mongodb shell
    • MongoDB port
    • MongoDB Query Operators
    • MongoDB Web Interface
    • MongoDB Query Array
    • MongoDB Transactions
    • MongoDB Not In
    • MongoDB not null
    • MongoDB npm
    • MongoDB Remove

Related Courses

MongoDB Certification Course

Oracle Certification Course

All in One Data Science Course

SQL Training Course

Oracle DBA Course

MS SQL Certification Course

MongoDB $elemMatch

By Sulaksh MoreSulaksh More

MongoDB $elemMatch

Introduction to MongoDB $elemMatch

The $elemMatch Operator of the MongoDB is used to find documents with at least one array field. The finding operation matches the data in the array field with the criteria mentioned with the $elemMatch. $elemMatch is an operator by MongoDB that is used to match elements in an array. MongoDB provides various operators for various operations, and $elemMatch seems to one of the underrated operators.

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,700 ratings)

Sample code:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

db.collectionname.find({"field": {$elemMatch: { $gte:11}}})

Such operators in MongoDB provides a great ability for the user to store and manage the data inside the documents.

Syntax with parameters:

{ <field>: { $elemMatch : { <query1>, <query2>, ... } } }

Breaking down the above syntax, starting with the field, which is the key, followed by the keyword $elemMatch and the selection criteria. Then, the query can be any basic comparison operator like equal to or greater than, etc. These comparison operators will filter out the expected result.

How MongoDB $elemMatch Operator works in MongoDB?

  • The $elemMatch operator is a simple search and filter operator, that looks for a passed value to be present in an array.
  • When we intend to find a document with specific criteria, we cannot use the same find method to work with arrays. Along with arrays, the $elemMatch operator comes in. The $elemMatch operator will search for the passed value inside the array of the documents, and when it matches, it will return the documents.
  • If the mentioned criteria match with no record or document present in the collection, it will return a blank. And if we execute this operator without a proper understanding of the array, or over an array with a massive amount of values, then it will result in high usage of CPU and get into doing scans over mini documents.
  • Now, two things are recommended not to use with $elemMatch operator. It is not a good practice to define $where operator along with the $elemMatch operator. And the $text operator should also not be used with the $elemMatch. It is an advantage of MongoDB being rich with its query language that we can access a document or records by its array values.

Examples of MongoDB $elemMatch

Given below are the examples of MongoDB $elemMatch:

Below is the screenshot of the collection, fun, which has multiple types of documents, within which are documents with array data types.

MongoDB $elemMatch 1

Example #1

Code:

db.fun.find({"results": {$elemMatch: {$gte: 81}}})

This query will find values, with the key of results, using the $elemMatch operator. Here $elemMatch operator will search for the values which are greater than equal to 81. We have used another operator here, which is $gte, which is used to filter the values and have the final result to be “Greater Than Equal To”.

So the first example is to find a value in the array, which is greater than equal to 81.

Output:

MongoDB $elemMatch 2

Above screenshot captures the proper output for the query 1. Our query has returned an array of values upon execution, which consists of a value greater than 81.

Example #2

We will add another comparison operator to the query.

Code:

db.fun.find({"results": {$elemMatch: {$gte: 41,$lt: 66}}})

Our second query extends the first one but adding another layer of filter here. It executes a find method on the fun collection, with $elemMatch operator, along with two query filters. We implemented a $gte operator in our first example. Like $gte, $lt is another operator that filters the records or the values to be “less than”.

Output:

add another comparison operator to the query

As we can see, our second query has returned several records. These records consist of an array with values greater than 41 and less than 66. There are documents with values larger than 66, like the last one with a value of 77, but we must consider that it contains the value which we intend to find, which is in the same record.

Example #3

For the third example, we will implement the $elemMatch operator over a string array. Until now we have successfully executed $elemMatch operator over an array of numbers, and the outputs are as expected.

Firstly, we have inserted a few records with array values of string.

inserted few records with array values of string

As shown, we have added a few cities and states names, as an array of string for few records. We will now execute our $elemMatch operator over these records.

Code:

db.fun.find({"results" :{ $elemMatch: { $eq : "Pune"}}})

Breaking down the above query, it is a simple find method over the fun collection, with $elemMatch operator for better filtering. Inside $elemMatch operator, we have a simple equation to the operator, which is $eq. This $eq operator will search and return every document or records that I collected with the value of Pune, inside the array.

Upon execution, this query will return records with Pune as a value in an array.

Output:

query will return records

As shown in the above screenshot, our query has been successful. It has retrieved every record that consisted of an array of string with the value of Pune. We implemented the $elemMatch operator with an array that includes numeric value and later with string values. In both cases, the working of $elemMatch was similar.

Conclusion

To conclude, MongoDB provides a wide range of operators, out of which $elemMatch is used to search and filter values, over an array. Based on the search criteria or the query, it will search for the matching records. Along with explanation, we implemented the $elemMatch operator over an array of numbers and then on an array of string too. The $elemMatch operator is highly recommended when in need of search operation. Every time we need to look inside an array, we use $elemMatch.

Recommended Articles

This is a guide to MongoDB $elemMatch. Here we discuss the introduction, how MongoDB $elemMatch operator works in MongoDB? and examples respectively. You may also have a look at the following articles to learn more –

  1. MongoDB Collection
  2. order by in MongoDB
  3. Mongo DB Create Database
  4. Advantages of MongoDB
Popular Course in this category
MongoDB Training Program (4 Courses, 2 Projects)
  4 Online Courses |  2 Hands-on Projects |  22+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Oracle Training (14 Courses, 8+ Projects)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
SQL Training Program (7 Courses, 8+ Projects)4.7
Oracle DBA Database Management System Training (2 Courses)4.7
MS SQL Training (16 Courses, 11+ Projects)4.7
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more