Video Transcript (English)
When querying a SQL database, we narrow our results by using operators like BETWEEN, and keywords such as ORDER BY and LIMIT.
In this SQL statement, we want to select every record’s city, state, and population from the zips table, where the state is NY, and the population is between 1000 and 5000. We also want to order the results by population in descending order and limit it to the first 10 results.
In MongoDB, the equivalent command to SQL SELECT is find.
The find method accepts a filter, projection, and options.
Knowing this, we can recreate our same SQL query in MongoDB by appending the find method to the zips collection in our database.
First, we provide filter criteria that specify two conditions that we want met.
In the first expression, we search for every document that has a state value of NY, similar to the WHERE clause.
In the second expression, we query for a population value between 1000 and 5000. In MongoDB, we use the “greater than or equal to” and “less than or equal to” comparison operators, which are labeled $gte and $lte, respectively.
By passing in a range of numbers, we filter our results in the same way that the SQL BETWEEN clause would.
Next, we pass in a projection document that excludes the _id and includes city, state, and population fields. You don’t have to do this step if you want to view the complete document for each entry.
We’re almost there!
Next, we can sort the results based on population. To do this in SQL, we used ORDER BY.
In MongoDB, we can do this by appending the .sort method to our query. Sort expects a field followed by a -1 for descending order or 1 for ascending order.
Finally, we use a limit method by passing in the number of documents that we want to return.
Let’s run this query in MongoDB. The results show multiple cities in New York that have a population between 1000 and 5000.
In this lesson, we learned the MongoDB equivalents to the SQL operators BETWEEN, ORDER BY, and LIMIT, which effectively map to greater than and less than, sort, and limit in MongoDB.