sqlmongodbdatabase

Converting SQL Queries to MongoDB Filters

SQL and MongoDB query syntax look nothing alike, but the logical operations map directly once you learn the operator equivalents.

5 min read

Related Tool

SQL to MongoDB

Open tool

Different Paradigms, Same Logic

SQL describes data retrieval declaratively using set operations. MongoDB queries use JSON-like filter documents with operator prefixes. The underlying logic — filter, project, sort, limit — is identical. The syntax is not.

Operator Mapping

| SQL | MongoDB |

|-----|---------|

| = value | { field: value } or { field: { $eq: value } } |

| != value | { field: { $ne: value } } |

| IN (a, b) | { field: { $in: [a, b] } } |

| NOT IN (a, b) | { field: { $nin: [a, b] } } |

| LIKE '%text%' | { field: { $regex: /text/i } } |

| > value | { field: { $gt: value } } |

| AND | { $and: [...] } or just combine keys in one object |

| OR | { $or: [...] } |

| IS NULL | { field: null } |

Common Pitfalls

JOINs: MongoDB does not have JOINs at the filter level — use $lookup in an aggregation pipeline. Transactions: multi-document transactions are supported but have different semantics than SQL. Type strictness: MongoDB stores typed BSON values; comparing a string field to an integer returns no results even if the numbers match visually.

Migration Strategy

When migrating from a relational database, convert simple SELECT + WHERE queries first. Aggregations, subqueries, and window functions require more significant restructuring into MongoDB aggregation pipelines.