Comparing With $gt, $lt and More

"Rated above 8.5" is not an equality test. For this you use a comparison operator. Instead of a plain value, the field gets a small document with the operator inside:

db.movies.find(
  { rating: { $gt: 8.5 } },
  { _id: 0, title: 1, rating: 1 }
)

Output:

[
  { title: 'Inception', rating: 8.8 },
  { title: 'Interstellar', rating: 8.7 }
]

{ rating: { $gt: 8.5 } } means "rating is greater than 8.5". Parasite and Whiplash are rated exactly 8.5, so they are not in the result. MongoDB's own keywords start with a dollar sign $. Here are the comparison operators:

OperatorMeaning
$gtgreater than
$gtegreater than or equal to
$ltless than
$lteless than or equal to
$nenot equal to

To check a range, put both conditions in the same operator document:

db.movies.find(
  { year: { $gte: 2014, $lte: 2016 } },
  { _id: 0, title: 1, year: 1 }
)

Output:

[
  { title: 'Interstellar', year: 2014 },
  { title: 'Whiplash', year: 2014 },
  { title: 'La La Land', year: 2016 }
]

This finds the movies from 2014 to 2016, with both years included.

Be careful with $ne. It also matches documents that do not have the field at all. In the lesson on flexible documents, you will see collections where some documents are missing a field.

In the exercise, find the movies released after 2015.