Convert SQL IN and NOT IN to MongoDB $in and $nin
Learn how SQL IN and NOT IN operators translate to MongoDB $in and $nin query operators for matching values against a list.
Detailed Explanation
IN / NOT IN to $in / $nin
SQL's IN operator checks whether a column value matches any value in a list. MongoDB provides the $in operator for the same purpose, and $nin for the negated form.
Example SQL
SELECT * FROM users
WHERE role IN ('admin', 'editor', 'moderator')
Generated MongoDB Query
db.users.find({
role: { $in: ["admin", "editor", "moderator"] }
})
NOT IN Example
SELECT * FROM products
WHERE category NOT IN ('archived', 'draft')
db.products.find({
category: { $nin: ["archived", "draft"] }
})
$in with Mixed Types
Unlike SQL where IN values typically share the same type, MongoDB's $in can contain mixed types:
db.items.find({ tag: { $in: ["featured", 1, true] } })
This flexibility comes from MongoDB's dynamic schema, but it is best to keep types consistent for predictable results.
$in on Array Fields
A powerful MongoDB-specific behavior is that $in works on array fields too. If a document has a field containing an array, $in matches if any element of the array is in the provided list. This has no direct SQL equivalent and is one of MongoDB's strengths for document-oriented data.
Performance
Both $in and $nin can use indexes. However, $nin typically requires a full collection scan because it must check that no value matches, making it less efficient than $in.
Use Case
Content management systems frequently filter articles by status (published, draft, review) or by category tags. Converting SQL IN queries demonstrates how MongoDB handles multi-value matching, which is fundamental for building dynamic content filters.
Try It — SQL to MongoDB Query
Related Topics
Convert SQL WHERE with Comparison Operators to MongoDB
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