So far, we’ve learned to query an array for exact matches, or individual elements. These are two extremes: searching for a specific ordering of elements, or only matching a single element. MongoDB offers us a middle ground. We can use the $all
operator to match documents for an array field that includes all the specified elements, without regard for the order of the elements or additional elements in the array.
For example, let’s say we’ve finished our young adult novel and are ready to move on to something that spans the science fiction and adventure genres. We could use the $all
operator to perform this query, like so:
db.books.find({ genres: { $all: [ "science fiction", "adventure" ] } })
This query might return the following documents:
{ _id: ObjectId(...), title: "Jurassic Park", author: "Michael Crichton", year_published: 1990, genres: ["science fiction", "adventure", "fantasy", "thriller"] }, { _id: ObjectId(...), title: "A Wrinkle in Time", author: "Madeleine L'Engle", year_published: 1962, genres: ["young adult", "fantasy", "science fiction", "adventure"] }, { _id: ObjectId(...), title: "Dune", author: "Frank Herbert", year_published: 1965, genres: ["science fiction", "fantasy", "adventure"] }, …
Notice that using the $all
operator will match documents where the given array field contains all the specified elements in any order, not necessarily the order provided in the query. Furthermore, our search returns documents where the genres
array includes other elements, in addition to the ones specified in our query.
Let’s practice writing queries with the $all
operator!
Instructions
Connect to the restaurants
database. Then, search the listingsAndReviews
collection for any restaurants where the michelin_stars
field has at least two award years: 2018 and 2019.