Learn

We’ve just learned how to execute queries that match an entire array where values are in a specific order. This is certainly useful, but it would be incredibly limiting if this were the only way we could query arrays. Fortunately, MongoDB gives us some additional syntax that we can use with .find() to make our searches more flexible.

First, we’ll learn how to match a single array element. Let’s return to our previous example where we are searching through a collection called books to find our next read. This was the structure we were working with:

{ _id: ObjectId(...), title: "Alice in Wonderland", author: "Lewis Carroll", year_published: 1865, genres: ["childrens", "fantasy", "literary nonsense"] }

Imagine we know we want to find a book that has the genre "young adult", but are otherwise open to any genre. Instead of providing the entire array as a query argument, we could provide just the value we want to match, like so:

db.books.find({ genres: "young adult" })

This would return all documents that have a genres field that is an array that contains the value "young adult", in addition to any other genres. Here is what our query might return:

{ _id: ObjectId(...), title: "Children of Blood and Bone", author: "Tomi Adeyemi", year_published: 2018, genres: ["fantasy", "young adult", "adventure"] }, { _id: ObjectId(...), title: "The Hunger Games", author: "Suzanne Collins", year_published: 2008, genres: ["young adult", "dystopian", "science fiction"] }, { _id: ObjectId(...), title: "The Black Flamingo", author: "Dean Atta", year_published: 2019, genres: ["young adult", "coming of age", "LGBTQ"] }, …

Note that every document in our result has a genres field that contains "young adult" as one of its values, in no particular order.

Before we move on, let’s practice querying for individual array elements!

Instructions

1.

Connect to the restaurants database. Then, search the listingsAndReviews collection for any restaurants that were awarded at least one Michelin Star in the year 2012.

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?