Lesson 13 +10 XP

Comparison Query Operators

Comparison Query Operators

Query operators compare and reference document fields when you filter in find() or other query methods.

The comparison operators

OperatorMeaning
$eqEqual to
$neNot equal to
$gtGreater than
$gteGreater than or equal to
$ltLess than
$lteLess than or equal to
$inMatches any value in an array

Using them

// Posts with exactly 3 likes
db.posts.find({ likes: { $eq: 3 } })

// Posts with more than 1 like
db.posts.find({ likes: { $gt: 1 } })

// Posts with 1 or fewer likes
db.posts.find({ likes: { $lte: 1 } })

// Posts with a category of News or Technology
db.posts.find({ category: { $in: ["News", "Technology"] } })

// Posts where likes is NOT 3
db.posts.find({ likes: { $ne: 3 } })

Implicit equality

A plain field/value query like { category: "News" } is shorthand for { category: { $eq: "News" } }.

TL;DR

  • $eq, $ne, $gt, $gte, $lt, $lte, $in compare field values.
  • { field: value } is the same as { field: { $eq: value } }.
  • $in matches if the value is in a given array.