Skip to content

Instantly share code, notes, and snippets.

@powertech2nd
Created March 5, 2026 11:45
Show Gist options
  • Select an option

  • Save powertech2nd/63645b6c82d2a170529d862f9bb2a17e to your computer and use it in GitHub Desktop.

Select an option

Save powertech2nd/63645b6c82d2a170529d862f9bb2a17e to your computer and use it in GitHub Desktop.

02 β€” Conditional Queries (Find Many)

Goal: Filter results based on status or numerical ranges. Key Idea: MongoDB uses Operators (words starting with $) instead of math symbols.


The Core Difference

SQL MongoDB Operator Meaning
= { field: value } Equals
> $gt Greater Than
>= $gte Greater Than or Equal
< $lt Less Than
<= $lte Less Than or Equal
!= $ne Not Equal
IN (...) $in: [...] Value is in array
NOT IN (...) $nin: [...] Value is not in array
AND , (comma) Both conditions must match
OR $or: [...] Either condition matches

Task: Find all "active" users over age 21

SQL Way

SELECT *
FROM Users
WHERE status = 'active'
  AND age > 21;

MongoDB Way

db.users.find({
  status: "active",
  age: { $gt: 21 }
});

πŸ” Breaking Down the MongoDB Syntax

db.users.find({
  status: "active",   // Plain equals: status = 'active'
  age: { $gt: 21 }    // Operator: age > 21
  //     ↑
  //   $gt wraps inside an object { }
});

More Examples

OR condition

-- SQL
SELECT * FROM Users WHERE status = 'active' OR status = 'pending';
// MongoDB
db.users.find({
  $or: [
    { status: "active" },
    { status: "pending" }
  ]
});

IN list

-- SQL
SELECT * FROM Users WHERE role IN ('admin', 'editor');
// MongoDB
db.users.find({
  role: { $in: ["admin", "editor"] }
});

Range (between)

-- SQL
SELECT * FROM Users WHERE age BETWEEN 18 AND 30;
// MongoDB
db.users.find({
  age: { $gte: 18, $lte: 30 }
});

πŸ’‘ Notes

  • Multiple conditions inside {} are treated as AND by default.
  • Operators always go inside an object: { $gt: 21 }, not $gt: 21 on its own.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment