Nice job! In this lesson, we learned how to query documents in MongoDB. Let’s recap some key takeaways from the lesson:
- We can view a list of all our databases by running the
- We can navigate to a particular database, or see which database we are currently using with the
use <db>, and
- We can use the
.find()method to query a collection. Excluding a
queryargument matches all documents from the collection.
- We can match documents on particular field values by passing a
queryargument to the
- When a collection’s record has an embedded document, we can query the fields inside of it using dot notation (
.) and wrapping the fields in quotation marks.
$ltcomparison operators allow our query to match documents where the value for a particular field is greater than or less than a given value, respectively.
- We can use the
.sort()method to sort our query results by a particular field in ascending or descending order.
- We can include a projection in our query to include or exclude certain fields from our returned documents.
In addition to the methods and operators we’ve covered in this lesson, MongoDB provides us with even more syntax that can be useful to us when performing queries:
.count()method returns the number of documents that match a query.
.limit()method can be chained to the
.find()method, and specifies the maximum number of documents a query will output.
$existsoperator can be included in a query filter to only match documents that contain the given field.
$neoperator helps check if a field is not equal to a specified value.
$oroperators help perform AND or OR logic operators.
Lastly, if you are looking for a way to make query outputs look a bit more “pretty”, you can use the
We have provided you with the
listingsAndReviews collection. Before moving on, spend some time experimenting with writing queries, using the syntax you learned throughout this lesson. If you are up for a challenge, try any of the following tasks listed below. Remember to first connect to the
restaurants database to access the
listingsAndReviews collection. Good luck, and click Up Next when you are ready to move on!
- Find all of the restaurants in the borough
"Japanese"cuisine sorted in reverse alphabetical order by name.
- Count the number of restaurants in the borough
"Manhattan"serving your favorite cuisine, limited to five results.
- Find all the restaurants in the borough
"Bronx"that serve one of the following cuisines:
"Juice, Smoothies, Fruit Salads",