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

Lesson 6, Exercise 1: Using the SQL Query tool to run SQL statements

MongoDB 201: Querying MongoDB Data Querying MongoDB with SQL SELECT Statements Lesson 6, Exercise 1: Using the SQL Query tool to run SQL statements

In this exercise, you’ll use the SQL Query tool to run several SQL statements that retrieve data from the customers collection.

The exercises in this section use the sales database and the customers collection. The first section in this course demonstrated how to create the database and import the collection. Refer to that section for details on how to set up the database and collection if you haven’t done so already.

To run the SQL statements

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, expand the sales database node and, if necessary, expand the Collections node for that database.

3. Right-click the customers collection node and click Open SQL. This launches the SQL Query tool, which opens as a tab in the main window, as shown in the following figure.

SQL database

The SQL tab is divided into two sections. The top section provides a command prompt for running SQL statements. When you first open the SQL tab, the command prompt is prepopulated with a SELECT statement that retrieves all data from the current collection. In this case, the statement is specific to the customers collection, as shown in the following code:

select *
from customers;

The bottom section of the SQL tab is similar to the bottom section of a collection tab, except that it also includes the SQL Query tab, which displays the SQL query associated with the current results. The tab’s contents are blank until you run an SQL statement.

4. Click the run button on the toolbar above the command prompt (third button from the left). SQL Query displays the query results in the Result tab in the lower section. The collection should include 1,000 documents.

The run button icon changes depending on whether you’ve selected SQL command text. When no text is selected, the button’s tooltip reads Execute SQL statement at cursor, and SQL Query runs the SQL statement where the cursor is positioned. When text is selected, the button changes, and the tooltip reads Execute selected SQL statement. SQL Query runs only the selected code.

5. Go to the Query Code tab. By default, Studio 3T displays the mongo shell statement used to retrieve all the documents from the customers collection, as shown in the following code.

use sales;
db.getCollection("customers").find({});

The statement calls the find method on the customers collection. Because no arguments are passed into the method, the statement returns all documents in the collection. 

6. At the command prompt in the SQL editor, replace the existing code with the following SELECT statement:

select first, last, interests
from customers;

The SELECT clause limits the results to the first, last, and interests columns, and the FROM clause specifies the customers collection as the target data source.

7. On the SQL Query toolbar, click the run button. The query should return all 1,000 documents, but only the first, last, and interests fields.

8. Go to the Result tab in the lower window and display the documents in Table View if not already displayed in that view.

9. If the values in the interests field are not displayed, right click one of the field’s values and click Show Embedded Fields. Your results should look similar to the following figure.

Result tab

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

select first, last, interests
from customers
where dob < ISODate('1990-01-01T00:00:00.000+0000');

The statement is similar to the previous one except that it now includes a WHERE clause, which limits the results to customers who were born before January 1, 1990.

11. Press F5 to run the SELECT statement. The statement should return only 812 documents, rather than the full 1,000.

The F5 shortcut is similar to clicking the run button when executing an SQL statement. Studio 3T supports a wide range of shortcuts that you can use throughout the interface to carry out tasks more quickly. You can find a list of shortcuts in the Studio 3T Knowledge Base article, Shortcuts.

12. At the command prompt in the SQL editor, replace the existing code with the following SELECT statement and then press F5 to run the statement:

select first, last, interests
from customers
where dob < ISODate('1990-01-01T00:00:00.000+0000')
order by last, first;

The statement adds an ORDER BY clause, which sorts the documents by the customers’ last names and then their first names. By default, the values are sorted in ascending order.

13. At the command prompt in the SQL editor, replace the existing code with the following SELECT statement and then press F5 to run the statement:

select first, last, interests
from customers
where dob < ISODate('1990-01-01T00:00:00.000+0000')
  and interests like '%database%'
order by last, first;

The statement expands the WHERE clause to limit the results further to those that include the term database in the list of values in the interests array.

The new search condition uses the LIKE operator and the percent (%) wildcard before and after the specified value. 

By using the wildcard, an array value can include the search term anywhere within the value for the document to be returned.

For example, the statement could return documents with any of the following array values: Database, databases, NoSQL databases, or Database SQL. Because of the added search condition, the query now returns only 17 documents.

14. At the command prompt in the SQL editor, replace the existing code with the following SELECT statement and then press F5 to run the statement:

select first, last, interests
from customers
where dob < ISODate('1990-01-01T00:00:00.000+0000')
  and (interests like '%database%'
    or interests like '%gaming%')
order by last, first;

The WHERE clause now includes an additional search condition stating that an array value can include either database or gaming (or both).

Notice that the two search conditions are connected with an OR operating, indicating either of the two conditions can evaluate to true for the document to be returned. The query now returns 33 documents.

15. Go to the Query Code tab. Notice that the find statement includes the query, projection, and sort sections.

The query section uses regular expressions to limit the results to those documents that contain either database or gaming in the interests array, as shown in the following figure.

Query code

The regular expressions are the values associated with the two interests array elements.

Forward slashes enclose each expression, followed by the i option, which indicates that the search condition is case-insensitive.

The expression itself begins with the carrot (^) anchor and ends with the dollar sign ($) anchor. These are added by default to help better utilize the indexes. 

The search term itself (database or gaming) begins and ends with the period/asterisk (.*) combination, which matches any alphanumeric character that appears zero or more times.

This makes it possible to find the search term regardless of where it appears in the array value.

16. At the command prompt in the SQL editor, replace the existing code with the following SELECT statement:

select first, last, interests, year(dob)
from customers
where dob < ISODate('1990-01-01T00:00:00.000+0000')
  and (interests like '%database%'
    or interests like '%gaming%')
order by last, first;

The statement is similar to the previous one, except that it adds the dob field to the SELECT clause, specifying the field name as an argument to the YEAR function. The function is used by multiple database management systems to extract the year from a date/time value.

17. Press F5 to run the statement. The statement returns an error stating that the YEAR function is not supported. As this demonstrates, SQL Query does not support all SQL statement elements.

If you encounter this issue, you’ll need to modify your statement, run it to verify whether it works, and then update the mongo shell code manually to get the exact results you want.

18. Leave the SQL tab open for the next exercise.

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
    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