Skip to content
Studio 3T - The professional GUI, IDE and client for MongoDB
  • Tools
    • Aggregation Editor
    • IntelliShell
    • Visual Query Builder
    • Export Wizard
    • Import Wizard
    • Query Code
    • SQL Query
    • Connect
    • Schema Explorer
    • Compare
    • SQL ⇔ MongoDB Migration
    • Data Masking
    • Task Scheduler
    • Reschema
    • More Tools and Features
  • Solutions
  • Resources
    • Knowledge Base
    • MongoDB Tutorials & Courses
    • Tool/Feature Documentation
    • Blog
    • Community
    • Testimonials
    • Whitepapers
    • Reports
  • Contact us
    • Contact
    • Sales Support
    • Feedback and Support
    • Careers
    • About Us
  • Store
    • Buy Now
    • Preferred Resellers
    • Team Pricing
  • Download
  • My 3T
search

Academy 3T

  • Explore our courses
    • MongoDB 101: Getting Started
    • MongoDB 201: Querying MongoDB Data
    • MongoDB 301: Aggregation
  • Get certified

Querying Arrays Using MongoDB $elemMatch

MongoDB 201: Querying MongoDB Data Querying Arrays Using MongoDB $elemMatch

Documents in a MongoDB database commonly include fields defined with the Array data type.

A field configured with this type can contain zero or more elements that together form a list—or array—of values. The values might all be the same data type, or they might be different types.

For example, an Array field might contain a mix of strings, integers, dates, embedded documents, or even other arrays.

When the documents in your collection contain arrays, you’ll likely want to build queries that can retrieve specific documents based on the values within those arrays.

To do so, you should understand the fundamentals of working with an array to ensure you can retrieve the documents you need when you need them.

In this section of the course, you’ll learn how to query a simple array in which all the values are configured with the String data type.

To build and run these queries, you’ll use both IntelliShell and Visual Query Builder in Studio 3T. This will allow you to learn the basics of querying MongoDB arrays, while also seeing how easy it is to build these queries using Visual Query Builder.

This section of the course focuses only on simple arrays whose values are all configured with the String data type. In the next section, you will learn how to work with more complex arrays that contain embedded documents.

Querying a MongoDB array

Throughout this course, you’ve been using the customers collection to learn different concepts.

The documents in this collection contain the interests field, which is an array that includes multiple String values, usually between two and four.

Although the field can contain any number of values and those values can be different types, this particular collection is limited to only a few String values.

The following figure shows a sample of the values in the interests array, as they appear on the Result tab of the customers collection tab.

Result page
Stepping into the interests array field/column in the Collection Tab

The figure provides a good cross section of the interests array. Although most documents include the Technology value, not all do, nor do the values appear in the same order. 

If you want to retrieve documents based on a single value in the array, you can use the collection’s find method, specifying the name of the array field and the target value, as shown in the following example:

use sales;
db.customers.find(
  { "interests": "Gaming" } );

The statement calls the find method on the customers collection in the sales database.

The method takes one argument, an embedded document that specifies the field name, followed by the value. In this case, the target field is interests and the target value is Gaming. 

The query will return only documents that contain the Gaming value in the interests array. It does not matter where the Gaming value falls within the array or how many values are included in the array. All that matters is that the array contains the specified element.

The MongoDB $elemMatch operator

When working with arrays, you might come across the $elemMatch operator. You’ll certainly see it when using Visual Query Builder to create statements based on array values.

The operator can be used with the find method or aggregate method to return documents in which at least one element in the array matches the method’s specified search criteria.

For example, you can recast the previous statement to include the $elemMatch operator, as shown in the following example:

use sales;
db.customers.find(
  { "interests": { $elemMatch: {$eq: "Gaming"} } } );

The statement returns the same results as the preceding one, but with the added complexity that comes with the $elemMatch operator.

The search condition in this case is the embedded document {$eq: "Gaming"}, which means a document must contain the Gaming value in the interests array in order to be returned, just like the previous statement.

As the two examples demonstrate, you don’t need to use the $elemMatch operator when specifying a single search condition.

The operator is mentioned here only because you’ll see it used in the code generated by Visual Query Builder, even when only one search condition is specified.

The next section of the course will cover the operator in more detail, where you’ll see examples that do benefit from the operator.

In the meantime, let’s consider how to build a query based on multiple array values, a process not quite as straightforward as a query based on a single value.

Suppose you want to return documents in which the interests array contains both the Gaming and Web Design values. In an attempt to build such a query, you might try the following statement:

use sales;
db.customers.find(
  { "interests": ["Gaming", "Web Design"] } );

Unfortunately, the query returns no documents from the customers collection because it’s looking for those that are an exact match.

In other words, the interests array must contain both the Gaming and Web Design values in the specified order and include no other array elements.

To return all documents that contain both values, you can instead use the $and operator to define two search conditions, one for Gaming and one for Web Design, as shown in the following example:

use sales;
db.customers.find(
  { 
    "$and": [
      { "interests": "Gaming" }, 
      { "interests": "Web Design" } ]
  } );

The statement returns only those documents in which the interests array contains both of the target elements. It does not matter what order they appear or whether the array contains other elements, as long the document includes both Gaming and Web Design.

If you want to return documents that include either value, you can instead use the $or operator:

use sales;
db.customers.find(
  { 
    "$or": [
      { "interests": "Gaming" }, 
      { "interests": "Web Design" } ]
  } );

Now only one of the two conditions needs to be true for a document to be returned, although a document can include both values.

By the end of this section, you will learn how to:

  • Use IntelliShell to query single and multiple values in an array
  • Use Visual Query Builder to query a single array value
  • Use Visual Query Builder to query multiple array values

What you will need:

  • Access to a MongoDB Atlas cluster
  • Access to the customers collection in the sales database
Lesson Content
0% Complete 0/4 Steps
Lesson 4, Exercise 1: Using IntelliShell to query single and multiple values in an array
Lesson 4, Exercise 2: Using Visual Query Builder to query a single array value
Lesson 4, Exercise 3: Using Visual Query Builder to query multiple array values
Test your skills: Querying Arrays Using MongoDB $elemMatch
MongoDB 201 Mid-Course Feedback
Previous Lesson
Back to Course
Next Topic
  • Course Home Expand All
    Performing MongoDB CRUD Operations
    4 Topics | 1 Quiz
    Lesson 1, Exercise 1: Adding a document to a collection
    Lesson 1, Exercise 2: Viewing a document in a collection
    Lesson 1, Exercise 3: Updating a document in a collection
    Lesson 1, Exercise 4: Deleting a document from a collection
    Test your skills: Performing CRUD Operations
    Building MongoDB find() Queries
    4 Topics | 1 Quiz
    Lesson 2: The MongoDB find method
    Lesson 2, Exercise 1: Using IntelliShell to build and run find statements
    Lesson 2, Exercise 2: Using Visual Query Builder to build and run find statements
    Lesson 2, Exercise 3: Using Query Code and IntelliShell to modify and run a find statement
    Test your skills: Building MongoDB find() Queries
    Working with the MongoDB Aggregation Pipeline
    6 Topics | 1 Quiz
    Lesson 3: Introducing the MongoDB aggregate method
    Lesson 3, Exercise 1: Filtering the documents in the aggregation pipeline
    Lesson 3, Exercise 2: Grouping the documents in the aggregation pipeline
    Lesson 3, Exercise 3: Adding and removing fields in the aggregation pipeline
    Lesson 3, Exercise 4: Changing the field order in the aggregation pipeline
    Lesson 3, Exercise 5: Sorting the documents in the aggregation pipeline
    Test your skills: Working with the MongoDB Aggregation Pipeline
    Querying Arrays Using MongoDB $elemMatch
    4 Topics | 1 Quiz
    Lesson 4, Exercise 1: Using IntelliShell to query single and multiple values in an array
    Lesson 4, Exercise 2: Using Visual Query Builder to query a single array value
    Lesson 4, Exercise 3: Using Visual Query Builder to query multiple array values
    Test your skills: Querying Arrays Using MongoDB $elemMatch
    MongoDB 201 Mid-Course Feedback
    Querying Embedded Documents in MongoDB Arrays
    3 Topics | 1 Quiz
    Lesson 5, Exercise 1: Using the $elemMatch operator to query embedded documents
    Lesson 5, Exercise 2: Using conditional operators to query embedded documents
    Lesson 5, Exercise 3: Using Visual Query Builder to query embedded documents
    Test your skills: Querying Embedded Documents in Arrays
    Querying MongoDB with SQL SELECT Statements
    2 Topics | 1 Quiz
    Lesson 6, Exercise 1: Using the SQL Query tool to run SQL statements
    Lesson 6, Exercise 2: Using the SQL Query tool to aggregate collection data
    Test your skills: Querying MongoDB with SQL
    Working with MongoDB Views
    3 Topics | 1 Quiz
    Lesson 7, Exercise 1: Creating a MongoDB view
    Lesson 7, Exercise 2: Querying a MongoDB view
    Lesson 7, Exercise 3: Modifying and deleting a MongoDB view
    Test your skills: Working with MongoDB Views
    Course Extras
    Return to MongoDB 201: Querying MongoDB Data
  • Studio 3T

    MongoDB Enterprise Certified Technology PartnerSince 2014, 3T has been helping thousands of MongoDB developers and administrators with their everyday jobs by providing the finest MongoDB tools on the market. We guarantee the best compatibility with current and legacy releases of MongoDB, continue to deliver new features with every new software release, and provide high quality support.

    Find us on FacebookFind us on TwitterFind us on YouTubeFind us on LinkedIn

    Education

    • Free MongoDB Tutorials
    • Connect to MongoDB
    • Connect to MongoDB Atlas
    • Import Data to MongoDB
    • Export MongoDB Data
    • Build Aggregation Queries
    • Query MongoDB with SQL
    • Migrate from SQL to MongoDB

    Resources

    • Feedback and Support
    • Sales Support
    • Knowledge Base
    • FAQ
    • Reports
    • White Papers
    • Testimonials
    • Discounts

    Company

    • About Us
    • Blog
    • Careers
    • Legal
    • Press
    • Privacy Policy
    • EULA

    © 2023 3T Software Labs Ltd. All rights reserved.

    • Privacy Policy
    • Cookie settings
    • Impressum

    We value your privacy

    With your consent, we and third-party providers use cookies and similar technologies on our website to analyse your use of our site for market research or advertising purposes ("analytics and marketing") and to provide you with additional functions (“functional”). This may result in the creation of pseudonymous usage profiles and the transfer of personal data to third countries, including the USA, which may have no adequate level of protection for the processing of personal data.

    By clicking “Accept all”, you consent to the storage of cookies and the processing of personal data for these purposes, including any transfers to third countries. By clicking on “Decline all”, you do not give your consent and we will only store cookies that are necessary for our website. You can customize the cookies we store on your device or change your selection at any time - thus also revoking your consent with effect for the future - under “Manage Cookies”, or “Cookie Settings” at the bottom of the page. You can find further information in our Privacy Policy.
    Accept all
    Decline all
    Manage cookies
    ✕

    Privacy Preference Center

    With your consent, we and third-party providers use cookies and similar technologies on our website to analyse your use of our site for market research or advertising purposes ("analytics and marketing") and to provide you with additional functions (“functional”). This may result in the creation of pseudonymous usage profiles and the transfer of personal data to third countries, including the USA, which may have no adequate level of protection for the processing of personal data. Please choose for which purposes you wish to give us your consent and store your preferences by clicking on “Accept selected”. You can find further information in our Privacy Policy.

    Accept all cookies

    Manage consent preferences

    Essential cookies are strictly necessary to provide an online service such as our website or a service on our website which you have requested. The website or service will not work without them.

    Performance cookies allow us to collect information such as number of visits and sources of traffic. This information is used in aggregate form to help us understand how our websites are being used, allowing us to improve both our website’s performance and your experience.

    Google Analytics

    Google Ads

    Bing Ads

    Facebook

    LinkedIn

    Quora

    Hotjar

    Functional cookies collect information about your preferences and choices and make using the website a lot easier and more relevant. Without these cookies, some of the site functionality may not work as intended.

    HubSpot

    Social media cookies are cookies used to share user behaviour information with a third-party social media platform. They may consequently effect how social media sites present you with information in the future.

    Accept selected