Learn

In the previous exercise, we briefly learned about MongoDB’s implicit equality operator $eq. MongoDB provides us with many more comparison query operators that we can use to match documents based on other measures of equality. In this exercise, we’ll learn how to match documents that are greater than or less than a specified value.

The greater than operator, $gt, is used in queries to match documents where the value for a particular field is greater than a specified value. Let’s have a look at the syntax for the $gt operator:

db.<collection>.find( { <field>: { $gt: <value> } } )

To see the $gt operator in action, consider the following collection of US National Parks:

{ name: "Yosemite National Park", state: "California", founded: 1890 }, { name: Crater Lake National Park, state: "Oregon", founded: 1902 }, { name: "Mesa Verde National Park", state: "Colorado", founded: 1906 }, { name: "Olympic National Park", state: "Washington", founded: 1909 }, …

To find all parks that were founded after the year 1900, we could execute the following query:

db.national_parks.find({ founded: { $gt: 1900 }});

This would return documents where founded is 1901 or greater:

{ name: Crater Lake National Park, state: "Oregon", founded: 1902 }, { name: "Mesa Verde National Park", state: "Colorado", founded: 1906 }, { name: "Olympic National Park", state: "Washington", founded: 1909 }

Note: If we wanted to include the year 1900 in our query, we could use the $gte, which will match all values that are greater than or equal to the specified value.

We can also match documents that are less than a given value, by using the less than operator, $lt. For example, if we reference our national_parks example above, we could select all parks that were founded before 1900 with the following query:

db.national_parks.find({ founded: { $lt: 1900 }});

This would return all documents where founded is 1899 or lower.

{ name: "Yosemite National Park", state: "California", founded: 1890 }

Note: Similar to the $gte operator, we can use $lte if we want to match all values that are less than or equal to the specified value.

While the examples we examined in this exercise match numerical values, it’s worth noting that these comparison operators can be used with any data type (e.g., letters).

Let’s practice using these operators to query our listingsAndReviews collection!

Instructions

1.

Connect to the restaurants database, then query the listingsAndReviews collection to retrieve a list of restaurants where the restaurant_id is greater than "50000000".

2.

Query the listingsAndReviews collection again, this time to find all the restaurants where the name of the street where the restaurant is located starts with the letter "C" or any alphanumeric character that comes before it.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?