MongoDB supports rich expressive query operators allowing complex filter conditions, range comparisons, array lookups, and regular expression pattern matches.
flowchart TD
A["Query Filter Object"] --> B["Comparison ($gt, $gte, $lt, $lte, $ne, $in)"]
A --> C["Logical ($and, $or, $nor, $not)"]
A --> D["Element ($exists, $type)"]
A --> E["Regex ($regex, $options)"]
import { MongoClient } from 'mongodb';
const uri = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(uri);
async function executeAdvancedQueries() {
try {
await client.connect();
const db = client.db('kodersolution_no_sql');
const products = db.collection('products');
// 1. Comparison & Range Query ($gte, $lte)
const priceRangeQuery = {
price: { $gte: 50, $lte: 200 }
};
const midRangeProducts = await products.find(priceRangeQuery).toArray();
console.log('Products between $50 and $200:', midRangeProducts.length);
// 2. Set Membership Query ($in)
const categoryQuery = {
category: { $in: ['Electronics', 'Hardware'] }
};
const categoryMatches = await products.find(categoryQuery).toArray();
console.log('Category Matches ($in):', categoryMatches.length);
// 3. Complex Logical & Regex Query ($and + $regex)
const complexQuery = {
$and: [
{ title: { $regex: 'mouse|keyboard', $options: 'i' } },
{ price: { $lt: 150 } }
]
};
const complexMatches = await products.find(complexQuery).toArray();
console.log('Regex + Price Filter Matches:', complexMatches);
} catch (err) {
console.error('MongoDB Query Operator Error:', err.message);
} finally {
await client.close();
}
}
executeAdvancedQueries();
/^search/) have collection indexes built./$search/i) cannot use indexes and require full collection scans.$in instead of Multiple $or: Prefer { field: { $in: [val1, val2] } } over { $or: [{ field: val1 }, { field: val2 }] } for better query optimization.Which MongoDB query operator checks if a field value matches any element within a specified array?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With