Learn

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 $all operator to the .find() method.
  • The $all operator 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 $elemMatch operator to the .find() method.
  • 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:

  • The $size operator is used with .find() to match any array with the specified number of elements.
  • The $in operator can be included in queries to match documents where the field is an array that contains at least one element in the specified array.
  • The $nin operator can be included in queries to match documents where the field is an array that contains no elements mentioned in the given array.

Instructions

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!

Optional Tasks:

  • 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 "B".

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?