MongoDB Query
MongoDB Query Filters: Operators and NoSQL Injection Prevention
MongoDB query filters match documents using nested objects and $-prefixed operators like $gte, $in, $or, and $regex. Writing clean filter objects—and validating user-supplied request data—gives you expressive search queries while defending against NoSQL operator injection.
Comparison and Logical Query Operators
Combine equality matches with range, membership, and logical operators to filter collections precisely.
| Operator | Meaning | Example |
|---|---|---|
$gt / $gte |
Greater than / or equal | { price: { $gte: 20, $lte: 100 } } |
$lt / $lte |
Less than / or equal | { stock: { $lt: 5 } } |
$in / $nin |
Matches any value in array | { status: { $in: ['paid', 'shipped'] } } |
$ne |
Not equal | { role: { $ne: 'banned' } } |
$or / $and |
Logical OR / AND array | { $or: [{ featured: true }, { rating: { $gte: 4.5 } }] } |
import { MongoClient } from 'mongodb';
function escapeRegex(text) {
return text.replace(/[.*+?^${}()|[\]\]/g, '\$&');
}
async function searchProducts(productsCollection, { keyword, minPrice, categories }) {
const filter = {};
if (typeof keyword === 'string' && keyword.trim() !== '') {
filter.name = { $regex: escapeRegex(keyword.trim()), $options: 'i' };
}
if (typeof minPrice === 'number') {
filter.price = { $gte: minPrice };
}
if (Array.isArray(categories) && categories.length > 0) {
filter.category = { $in: categories.map(String) };
}
return productsCollection.find(filter).limit(25).toArray();
}
Preventing NoSQL Operator Injection
If an attacker sends JSON {"email": {"$ne": null}} to a login route and your code passes req.body.email straight into users.findOne({ email: req.body.email }), MongoDB matches the very first user in the database! Always validate and cast inputs to primitives (String(req.body.email) or Zod schemas) before placing them into query filters.
Common Mistakes to Avoid
- Passing unvalidated
req.bodyobjects intofindOne(): An object containing{"$gt": ""}turns an equality check into an operator match. Enforce string/number types first. - Passing raw user text into
$regexwithout escaping: Typing(or[in a search box crashes$regexwith a regex syntax error unless escaped withescapeRegex(). - Using unanchored case-insensitive
$regexon huge collections: Leading-wildcard regexes cannot use standard B-tree indexes efficiently; consider MongoDB Atlas Search or$textindexes for full-text search.
Frequently Asked Questions
How do I check if a field exists inside a document?
Use { deletedAt: { $exists: false } } or { deletedAt: null } (note that $exists: false matches only documents missing the field, whereas null matches both missing fields and explicit null values).
How do I query nested sub-document fields in MongoDB?
Use quoted dot notation, such as { 'address.city': 'Dhaka' }.
How do I match elements inside an array field?
To match documents whose tags array contains 'nodejs', pass { tags: 'nodejs' } directly, or { tags: { $all: ['nodejs', 'mysql'] } } when all listed tags must be present.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.