Core Operations
Querying and Filtering
Write powerful queries with MongoDB operators for complex filtering and comparison.
Query Operators
MongoDB provides rich query operators:
Comparison: $eq, $ne, $gt, $gte, $lt, $lte, $in, $nin
Logical: $and, $or, $not, $nor
Element: $exists, $type
Array: $all, $elemMatch, $size
String: $regex — regular expression matching
Dot Notation
Access nested fields and array elements using dot notation: "address.city", "items.0"
Sorting, Skip, Limit
Use these for pagination: .sort({ field: 1 }), .skip(n), .limit(n)
Example
javascript
const col = db.collection('products');
// Comparison operators
const expensive = await col.find({ price: { $gt: 100 } }).toArray();
const midRange = await col.find({ price: { $gte: 50, $lte: 200 } }).toArray();
const electronics = await col.find({ category: { $in: ['Electronics', 'Computers'] } }).toArray();
const notElectronics = await col.find({ category: { $nin: ['Electronics'] } }).toArray();
// Logical operators
const premiumApple = await col.find({
$and: [{ brand: 'Apple' }, { price: { $gt: 500 } }]
}).toArray();
const cheapOrOld = await col.find({
$or: [{ price: { $lt: 10 } }, { createdAt: { $lt: new Date('2020-01-01') } }]
}).toArray();
// Element operators
const withDiscount = await col.find({ discount: { $exists: true } }).toArray();
// Array operators
const taggedSale = await col.find({ tags: { $all: ['sale', 'featured'] } }).toArray();
// elemMatch - match array elements with multiple conditions
const reviews = await col.find({
reviews: { $elemMatch: { rating: { $gte: 4 }, verified: true } }
}).toArray();
// Dot notation for nested documents
const parisUsers = await db.collection('users').find({
'address.city': 'Paris'
}).toArray();
// Regex search
const appleProducts = await col.find({
name: { $regex: /apple/i }
}).toArray();
// Pagination
const page = 2, pageSize = 10;
const results = await col.find({})
.sort({ createdAt: -1 })
.skip((page - 1) * pageSize)
.limit(pageSize)
.toArray();Want to run this code interactively?
Try in Compiler