CRUD OperationsCore· 35 min read

Query Operators, Sort & Limit

Ask precise questions — greater than, in a list, sorted, limited — with query operators.

What you will learn

  • Use comparison operators ($gt, $lt, $in)
  • Sort results
  • Limit how many come back

Comparison operators

Operators start with $ and go inside the filter to express conditions.

OperatorMeans
$gt / $ltGreater / less than
$gte / $lteGreater-or-equal / less-or-equal
$neNot equal
$inMatches any value in a list
Query operators in action
// Users older than 21
db.users.find({ age: { $gt: 21 } })

// Users in selected cities
db.users.find({ city: { $in: ["Bengaluru", "Mumbai"] } })

The trick is that the value of a field becomes a little object holding the operator. { age: { $gt: 21 } } reads as “age greater-than 21”, so it returns everyone aged 22 and up. { city: { $in: [...] } } reads as “city is any one of these values”, so it returns users from Bengaluru or Mumbai. Without an operator, { age: 21 } would mean exactly equal to 21.

Note: Output (first query): [ { name: 'Asha', age: 22, ... }, { name: 'Ravi', age: 25, ... } ] Meera (age 23) and anyone over 21 also appears; anyone aged 21 or under is left out.

Sort and limit

Once you have your matches you often want them in order and trimmed to a few. sort() orders the results by a field and limit() keeps only the first N. Together they answer questions like “the 3 oldest users”.

sort then limit
// Top 3 oldest users
db.users.find().sort({ age: -1 }).limit(3)
//  sort: 1 = ascending, -1 = descending

Read it left to right: find() gets all users, .sort({ age: -1 }) orders them by age from highest to lowest (the -1 means descending; 1 would mean smallest-first), and .limit(3) keeps only the top 3 of that ordered list. Change -1 to 1 and you would get the 3 *youngest* instead.

Note: Output: [ { name: 'Ravi', age: 25 }, { name: 'Meera', age: 23 }, { name: 'Asha', age: 22 } ] The oldest user comes first because of the descending sort, and only three documents come back because of the limit.

Tip: Chain them like array methods: find(...).sort(...).limit(...). This is exactly how you build “latest 10 posts” or “top 5 products” queries.

Q. Which operator matches values greater than a number?

Answer: $gt means “greater than”. Related: $lt (less than), $gte/$lte (or-equal), $ne (not equal), $in (in a list).

✍️ Practice

  1. Find documents where a number field is greater than a value.
  2. Sort results descending and limit to the top 5.

🏠 Homework

  1. Find the 3 most expensive products, sorted by price descending.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →