Let’s create our first SQL Query in MongoDB!
- If you haven’t already, download Studio 3T
- and the Customers data-set. (You’ll also find the data-set at the bottom of the article)
We want to find all customers from our data-set who:
- have <20 transactions
- and live in a town called “New York” or “Berlin”.
- To start building our query, let’s open the SQL Query feature in Studio 3T.
- 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.
- And our query looks like this…
where transactions < 20
and (address.city = 'Berlin'
or address.city = 'New York');
- Run the query
Running the query gives us…
19 customers – all of whom live in a ‘Berlin’ or ‘New York’.
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!