Well done! In this lesson, we continued our exploration of querying in MongoDB by learning how to query array fields. Let’s recap some important takeaways from this lesson:
- We can query documents for exact array matches by using the
.find()method and passing in a query document containing the field name, and its array as the value.
- We can match a single array element by using the
.find()method and passing in a query document containing the field name, and the element we want to match as its value.
- To match multiple elements in an array, we can apply the
$alloperator to the
$alloperator will match any document where the given array field contains all the specified values, in any order and regardless of other elements in the array.
- We can use the
.find()method with comparison operators to match documents where the array contains one or more elements that satisfy the query conditions in some combination.
- To match documents where the array contains one or more elements that satisfy all the query conditions, we can apply the
$elemMatchoperator to the
- We can query embedded documents in an array field by querying for either an exact match (with the exact order) or by querying for a single field.
In addition to the syntax we’ve covered in this lesson, MongoDB provides us with even more operators that can be useful to us when querying on array fields:
$sizeoperator is used with
.find()to match any array with the specified number of elements.
$inoperator can be included in queries to match documents where the field is an array that contains at least one element in the specified array.
$ninoperator can be included in queries to match documents where the field is an array that contains no elements mentioned in the given array.
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 the restaurants that have received a Michelin star exactly 14 times.
- Find all the restaurants that have received a Michelin star every year from 2006 to 2016.
- Find all the restaurants that have received only grades above a