Learn

More often than not, when we specify multiple query conditions for an array field, we’ll want to match at least one array element that meets all the filter criteria. We can accomplish this by using another operator, $elemMatch.

The $elemMatch operator is used in queries to specify multiple criteria on the elements of an array field, such that any returned documents have at least one array element that satisfies all the specified criteria.

Let’s reconsider our previous example about professional tennis players to see $elemMatch in action. Recall that documents from this collection have the following structure:

{ _id: ObjectId(...), name: "Serena Williams", country: "United States", wimbledon_singles_wins: [2002, 2003, 2009, 2010, 2012, 2015, 2016] }

Imagine that we want to search our collection again, this time, for any athletes who have won the Wimbledon Singles Championship in the current millennium, between the years 2000 and 2019.

Our query would look something like this:

db.tennis_players.find({ wimbledon_singles_wins: { $elemMatch: { $gte: 2000, $lt: 2020 } } })

This would only return documents whose wimbledon_singles_wins field is an array containing at least one element that is both greater than or equal to 2000 and less than 2020. Our resulting cursor might contain the following documents:

{ _id: ObjectId(...), name: "Pete Sampras", country: "United States", wimbledon_singles_wins: [1993, 1994, 1995, 1997, 1998, 1999, 2000] }, { _id: ObjectId(...), name: "Serena Williams", country: "United States", wimbledon_singles_wins: [2002, 2003, 2009, 2010, 2012, 2015, 2016] }, { _id: ObjectId(...), name: "Roger Federer", country: "Switzerland", wimbledon_singles_wins: [2003, 2004, 2005, 2006, 2007, 2009, 2012, 2017] }

Note that while any matching documents must contain at least one value in the wimbledon_singles_wins array that is between the range of 2000 and 2020, this array can also include values that fall outside that range.

Let’s practice querying arrays using the $elemMatch operator!

Instructions

1.

Connect to the restaurants database. Then, search the listingsAndReviews collection for any restaurants that were awarded a Michelin star between the years 2005 and 2010, inclusive.

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?