Convert SQL WHERE with Comparison Operators to MongoDB
Learn how SQL WHERE clauses with =, !=, >, <, >=, <= operators map to MongoDB query operators like $eq, $ne, $gt, $lt, $gte, $lte.
Detailed Explanation
Comparison Operators: SQL to MongoDB
SQL WHERE clauses with comparison operators translate directly to MongoDB query operators inside the filter document passed to find().
Example SQL
SELECT * FROM products
WHERE price >= 100 AND stock > 0
Generated MongoDB Query
db.products.find({
price: { $gte: 100 },
stock: { $gt: 0 }
})
Operator Mapping Table
| SQL Operator | MongoDB Operator | Example |
|---|---|---|
= |
implicit / $eq |
{ status: "active" } |
!= or <> |
$ne |
{ status: { $ne: "deleted" } } |
> |
$gt |
{ age: { $gt: 21 } } |
>= |
$gte |
{ price: { $gte: 100 } } |
< |
$lt |
{ quantity: { $lt: 5 } } |
<= |
$lte |
{ rating: { $lte: 3 } } |
Implicit AND
When multiple conditions are placed in the same filter document (as shown above), MongoDB treats them as an implicit AND. This is equivalent to SQL's AND keyword and is the most common pattern for combining conditions.
Equality Shorthand
For equality checks, MongoDB uses a shorthand where the value is placed directly: { status: "active" } instead of { status: { $eq: "active" } }. Both forms work, but the shorthand is more idiomatic and widely used.
Type-Aware Comparisons
MongoDB comparisons are type-aware. Comparing a string field with a number will not produce matches, unlike some SQL databases that perform implicit type casting. Ensure your filter values match the stored data types.
Use Case
API endpoints that filter product catalogs by price range, stock availability, or rating thresholds are among the most common queries in e-commerce applications. Understanding the comparison operator mapping is essential for any SQL-to-MongoDB migration.
Try It — SQL to MongoDB Query
Related Topics
Convert SQL IN and NOT IN to MongoDB $in and $nin
Filtering
Convert SQL LIKE to MongoDB $regex for Pattern Matching
Filtering
Convert SQL BETWEEN to MongoDB $gte and $lte Range Query
Filtering
Convert SQL IS NULL / IS NOT NULL to MongoDB Null Queries
Advanced
Convert SQL AND/OR Conditions to MongoDB $and/$or Operators
Advanced