MongoDB Query Fundamentals

In MongoDB, queries are built using a filter document that specifies conditions. The find() method returns all documents matching those conditions. Unlike SQL's WHERE clause, MongoDB queries use operators (prefixed with $) to express complex logic.

In this lesson, you'll query the FreshBasket e-commerce database and learn to use comparison operators, logical operators, array operators, projections, and pagination. By the end, you'll be able to retrieve exactly the data you need.

Comparison Operators

Comparison operators allow you to filter documents based on numerical or value ranges. Here are the most common ones:

$gt — Greater than (>). Returns docs where field value is strictly greater.

$gte — Greater than or equal (>=). Includes the boundary value.

$lt — Less than (<). Returns docs where field value is strictly smaller.

$lte — Less than or equal (<=). Includes the boundary value.

$ne — Not equal (!=). Returns docs where field does not match the value.

Q1: Find Products Over a Certain Price

Let's find all products in the products collection with a price greater than $10:

javascript
{ _id: ObjectId(...), name: "Organic Apples", category: "Fruits", price: 12.50, stock: 45 }
{ _id: ObjectId(...), name: "Greek Yogurt", category: "Dairy", price: 8.99, stock: 30 } — filtered out (not > 10)

Q2: Find Products Within a Price Range

Combine multiple comparison operators to find products priced between $5 and $15:

javascript
{ _id: ObjectId(...), name: "Organic Apples", category: "Fruits", price: 12.50, stock: 45 }
{ _id: ObjectId(...), name: "Greek Yogurt", category: "Dairy", price: 8.99, stock: 30 }

Q3: Find Products with Low Stock

Find all products with stock less than 20 units:

javascript
{ _id: ObjectId(...), name: "Premium Honey", category: "Condiments", price: 18.50, stock: 15 }

Logical Operators

Logical operators allow you to combine multiple conditions. The most important is implicit AND — when you specify multiple fields in a filter, MongoDB requires all conditions to be true.

Implicit AND

Specify multiple conditions in the same filter object. All must be true for a document to match:

javascript
Returns documents where category is "Fruits" AND price is greater than 10

Explicit AND with $and

Use $and when you need to combine the same field with multiple operators or for clarity:

javascript
Returns documents matching ALL three conditions

Q4: OR Operator

Use $or when at least one condition should be true:

javascript
Returns documents where category is "Fruits" OR "Dairy" (or both)

Q5: IN Operator

Use $in to match any value in a list. This is cleaner than multiple $or conditions:

javascript
Returns documents where category matches any of the three values

Q6: NOT IN Operator

Use $nin (not in) to exclude certain values:

javascript
Returns all documents except those in Frozen or Prepared categories

Q7: NOT Operator

Use $not to negate a condition:

javascript
Returns documents where price is NOT greater than 20 (i.e., price <= 20)

Element & Array Operators

MongoDB documents often contain arrays. These operators help you query array fields and check for field existence.

Q8: $exists Operator

Check whether a field exists in a document:

javascript
Returns all documents that have a 'supplier' field, regardless of its value

Q9: $type Operator

Match documents where a field has a specific data type:

javascript
Returns documents where 'stock' is an integer

Q10: $elemMatch Operator

Query array elements with multiple conditions. Perfect for arrays of objects:

javascript
Returns documents that have at least one review with rating >= 4 AND verified = true

Q11: $size Operator

Match arrays with a specific length:

javascript
Returns documents where the 'tags' array has exactly 3 elements

Projections — Select Specific Fields

Projections control which fields are included or excluded from query results. This is useful for reducing network traffic and focusing on relevant data. The second parameter of find() is the projection document.

Q12: Include Specific Fields

Use 1 to include fields. Return only name and price:

javascript
{ _id: ObjectId(...), name: "Organic Apples", price: 12.50 }
{ _id: ObjectId(...), name: "Greek Yogurt", price: 8.99 }
Note: _id is included by default

Q13: Exclude Specific Fields

Use 0 to exclude fields. Hide the stock field:

javascript
Returns all fields except stock and supplier

Q14: Exclude _id Field

The _id field is always included unless you explicitly exclude it:

javascript
{ name: "Organic Apples", price: 12.50 }
{ name: "Greek Yogurt", price: 8.99 }

Q15: Nested Field Projection

Project nested fields using dot notation:

javascript
Returns only customer name, email, and order total for each document

Sorting, Limiting & Pagination

Control the order and size of result sets using chainable methods: sort(), limit(), and skip(). These are called after find().

Q16: sort() — Order Results

Sort by price ascending (1) or descending (-1):

javascript
Returns all products ordered by price from lowest to highest

Sort descending by price, then ascending by name:

javascript
Returns products sorted by price (high to low), then by name (A to Z) for same-price items

Q17: limit() — Restrict Result Count

Return only the first 10 products:

javascript
Returns only the first 10 documents

Q18: skip() + limit() — Pagination

Implement pagination by skipping a number of documents, then limiting results:

javascript
Returns documents 21-30 (skip first 20, then take 10). Great for "Page 3" of results.

Q19: Complete Chained Query

Combine filter, projection, sort, and pagination for a real-world scenario:

javascript
Returns top 5 fruits priced >= $5, sorted by price (high to low), showing only name, price, and stock

Q20: Get Unique Values with distinct()

The distinct() method returns an array of unique values for a field:

javascript
[ "Fruits", "Dairy", "Vegetables", "Condiments", "Beverages" ]

You can also filter before getting distinct values:

javascript
[ "Fresh Farms Co", "Premium Imports", "Organic Valley" ]

Challenge

Write a query to find the top 3 most expensive products in the "Vegetables" category, showing only the name and price:

  • Filter: category = "Vegetables"
  • Projection: show only name and price, exclude _id
  • Sort: by price descending
  • Limit: 3 results
Show hint

Chain together find(), projection in second parameter, sort(), and limit():

javascript

Test Your Knowledge

Question 1 of 5
What's the difference between $gt and $gte?
Question 2 of 5
How does implicit AND work in MongoDB?
Question 3 of 5
What does the projection {name: 1, _id: 0} return?
Question 4 of 5
How do you paginate results to get page 3 (10 items per page)?
Question 5 of 5
What does distinct() return?
0
/5
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

You can now query any MongoDB collection.

Join the Best AI Program: The AI-Era Data Engineer — 5 months, fully online, with placement assistance. Week 1 is free.

Explore The AI-Era Data Engineer →