Try Studio 3T for Free
  1. Knowledge Base
  2. MongoDB Tutorials
  3. Create Your First SQL Query

Create Your First SQL Query

Let’s create our first SQL Query in MongoDB!

Requirements

  1. If you haven’t already, download Studio 3T
  2. and the Customers data-set. (You’ll also find the data-set at the bottom of the article)

The Task

We want to find all customers from our data-set who:

  • have <20 transactions
  • and live in a town called “New York” or “Berlin”.

The Query

  1. To start building our query, let’s open the SQL Query feature in Studio 3T.

    You’ll find it in the Global Toolbar or use the shortcuts : Shift + Ctrl + L (Shift + ⌘+ L)

  2.  The query itself has 5 defining conditions
    • SELECT – defines the range of documents to be queried
    • FROM – defines where the data should be searched – e.g. what collection(s)
    • WHERE – is the clause that starts filtering the results that fit our query
    • AND – is a conjunctive operator that defines the where clause
    • OR – also a conjunctive operator that is combined with the AND operator to further define our query.
  3. And our query looks like this…select *
    from Customers
    where transactions < 20
    and (address.city = 'Berlin'
    or address.city = 'New York');
  4. Run the query

The Results

Running the query gives us…

The query returns 19 customers who live in either 'Berlin' or 'New York'. Congratulations upon creating your first SQL query in MongoDB!

19 customers – all of whom live in a ‘Berlin’ or ‘New York’.

Don’t be alarmed if your results return different names!

Congratulations, you’ve now successfully created your first SQL query in MongoDB! If you’re looking for something more advanced, try your hand at using SQL joins to Query MongoDB!

Updated on December 5, 2019

Article Attachments

Was this article helpful?

Related Articles