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
    • Reports
    • Case Studies
    • Whitepapers
    • Blog
    • Testimonials
    • Community
  • Contact us
    • Contact
    • Sales Support
    • Feedback and Support
    • Career
    • About Us
  • Store
    • Buy Now
    • Preferred Resellers
    • Team Pricing
  • My License
  • Download
search

Academy 3T

  • MongoDB 101: Getting Started
  • MongoDB 201: Querying MongoDB Data
  • MongoDB 301: Aggregation

Lesson 4, Exercise 1: Using IntelliShell to query single and multiple values in an array

MongoDB 201: Querying MongoDB Data Querying Arrays Using MongoDB $elemMatch Lesson 4, Exercise 1: Using IntelliShell to query single and multiple values in an array

In this exercise, you’ll use IntelliShell to create and run several queries that retrieve data from the customers collection. The queries will be based on values in the interests array.

You’ll be working with the customers collection from the sales database we created in a previous section. Refer to that section for details on how to set them up if you haven’t done so already.

To build the queries in IntelliShell

1. Launch Studio 3T and connect to MongoDB Atlas.

Don’t have a MongoDB Atlas instance? Here’s how to set up a free cluster, or connect to an existing MongoDB database or localhost instead.

2. In the Connection Tree, right-click the sales database node and click Open IntelliShell. Studio 3T opens IntelliShell in its own tab in the main window.

3. On the IntelliShell toolbar, you’ll see that both the Auto-Completion button (the lightning bolt icon) and Query Assist button are already enabled by default. Make sure that both buttons are enabled. These will make it easier to view the results returned by the mongo shell commands.

4. At the command prompt in the IntelliShell editor, replace any existing code with the following find statement:

db.customers.find(
  { "interests": { $elemMatch: {$eq: "Database"} } }, 
  { "last" : 1.0, "interests": 1.0 } );

The statement uses the $elemMatch operator to match documents that contain the Database value in the interests array.

As long as any array element matches the operator’s search condition ({$eq: "Database"}), the document will be returned. In other words, the results will include any document that has an array value that equals Database.

The statement also limits the results to the last and interests fields, which are specified as the second argument passed to the find method.

The 1.0 value associated with each field indicates that the field should be included in the results, as opposed to being excluded.

5. On the IntelliShell toolbar, click the Run entire script button (Execute entire script). Studio 3T runs the find statement and returns the results in the bottom window, displaying them in the Find Query tab. 

6. The Find Query tab displays results in Table View. Choose Table View if it’s not already selected.

7. If the values in the interests array are not displayed, right-click one of the values in the interests column and then click Show Embedded Fields. 

alt="Show embedded fields"

The query should have returned 22 documents. The following figure shows part of those results. Notice that the Database value can appear in any position within the array.

8. At the command prompt in the IntelliShell editor, replace the existing code with the following find statement:

db.customers.find(
  { interests: "Database" }, 
  { "last" : 1.0, "interests": 1.0 } );

The statement returns the same results as the previous find statement; however, you do not need to use the $elemMatch operator because you’re defining only one search condition.

9. On the IntelliShell toolbar, click the Run entire script button. The statement should return the same 22 rows as the previous example.

10. At the command prompt in the IntelliShell editor, replace the existing code with the following find statement:

db.customers.find(
  { "interests.0": "Web Design" }, 
  { "last" : 1.0, "interests": 1.0 } );

The statement uses dot notation (interest.0) to specify the index position when verifying values in the interests array.

MongoDB indexes are zero-based, so interests.0 refers to the first position in the interests array. As a result, the statement will return only documents whose first value in that array is Web Design.

When using dot notation in this way, you must enclose the field and index position in quotation marks.

If you refer to the preceding example, you’ll see that the interests field name, when used alone, does not need to be enclosed in quotes, although quotation marks can be used.

11. Run the entire script. The query should return only three documents. For each document, the first value in the interests array should be Web Design.

12. At the command prompt in the IntelliShell editor, replace the existing code with the following find statement:

db.customers.find(
  { interests: { $size: 4 } }, 
  { "last" : 1.0, "interests": 1.0 } );

The statement uses the $size operator to specify that the interests array should include exactly four elements for the document to be returned.

13. Run the entire script. The query should return seven documents, each containing four values in the interests array.

14. At the command prompt in the IntelliShell editor, replace the existing code with the following find statement:

db.customers.find(
  { 
    "$and": [
      { "interests": { $elemMatch: { $eq: "Database" } } }, 
      { "interests": { $elemMatch: { $eq: "Web Design" } } } ]
  }, 
  { "last" : 1.0, "interests" : 1.0 } );

The statement uses the $and operator to define two search conditions that must both evaluate to true for a document to be returned.

Each search condition uses the $elemMatch operator to indicate that the interests array must contain the specified values (Database and Web Design, respectively).

15. Again, run the entire script. This time, the statement returns only two documents.

16. Now, right-click one of the values in the interests column and then click Show Embedded Fields.

Each document includes the Database and Web Design values in the interests array, as shown in the following figure.

execute script

17. At the command prompt in the IntelliShell editor, replace the existing code with the following find statement:

db.customers.find(
  { 
    "$and": [
      { "interests": "Database" }, 
      { "interests": "Web Design" } ]
  }, 
  { "last" : 1.0, "interests" : 1.0 } );

The statement works just like the previous one, except that it does not use the $elemMatch operator, helping to simplify the overall statement.

18. Click the Run entire script button. You should receive the same results as the previous statement.

19. Replace the existing code with the following find statement:

db.customers.find(
  { "interests": { $all: ["Database", "Web Design"] } }, 
  { "last" : 1.0, "interests" : 1.0 } );

Rather than using the $and operator, the statement uses the $all operator, which provides a simple way to specify that returned documents should include certain values in the target array.

The values themselves are passed to the $all operator as an array, which in this case includes the Database and Web Design elements.

20. Run the entire script again. You should receive the same results as the previous two statements.

21. Close the IntelliShell tab. If prompted to save your changes, click No.

Next – Lesson 4, Exercise 2: Using Visual Query Builder to query a single array value
Previous Lesson
Back to Lesson
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
    3 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
    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
    • Case Studies
    • White Papers
    • Testimonials
    • Discounts

    Company

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

    © 2022 3T Software Labs GmbH. All rights reserved.

    • Privacy Policy
    • Cookie settings
    • Impressum
    When you click "Accept", you are agreeing to cookies being on your device. They may improve site navigation, site usage analysis, or the relevance of messages. It is up to you which cookies are enabled. Read our Privacy Policy.
    Manage cookies
    Accept
    ✕

    Privacy Preference Center

    A cookie is a small file of letters and numbers that is downloaded on to your computer when you visit a website. Cookies are used by many websites and can do a number of things, eg remembering your preferences, recording what you have put in your shopping basket, and counting the number of people looking at a website. In the form below you can choose which cookies, except for essential cookies, to allow or disable.

    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.

    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.

    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