MongoDB provides a wide range of operators for both simple queries and complex aggregation pipelines. The following comparison opertaors are frequently used with the find() method:
$gt– greater than$lt– less then$gte– greater than or equal to$lte– less than or equal to$ne– not equal
Example: fetch products with a stock count above 50 and a price less then 100:
db.inventory.find({
qty: { $gt: 50 },
price: { $lt: 100 }
})
Aggregation pipelines unlock more advanced data processing. A common pipeline starts with $match (like find()) and then transforms the records with stages such as $project, $group, $limit, or $skip.
Assume a sales collection:
{ _id: 1, item: "widget", price: 12, quantity: 3, saleDate: ISODate("2024-01-15") }
{ _id: 2, item: "gadget", price: 25, quantity: 1, saleDate: ISODate("2024-02-10") }
{ _id: 3, item: "widget", price: 12, quantity: 8, saleDate: ISODate("2024-02-20") }
$project – Reshape Documents
$project selects specific fields, creates computed fields, and can suppress the _id. To show item, price, and a new field revenue:
db.sales.aggregate([
{ $project: { _id: 0, item: 1, price: 1, revenue: { $multiply: ["$price", "$quantity"] } } }
])
$match – Filter before Aggregating
Place $match early to reduce later processing. Retrieve all sales where the quantity is at least 3:
db.sales.aggregate([
{ $match: { quantity: { $gte: 3 } } },
{ $group: { _id: "$item", totalQty: { $sum: "$quantity" } } }
])
$limit and $skip
For pagination, $skip ignores the first N documents and $limit restricts the output size.
db.sales.aggregate([
{ $skip: 10 },
{ $limit: 5 }
])
$cond – Conditional Expressions
$cond mimics an if-then-else logic inside stage expressions. Below, a discount factor is applied based on quantity:
db.sales.aggregate([
{ $project: {
item: 1,
price: 1,
factor: {
$cond: { if: { $gte: ["$quantity", 5] }, then: 0.85, else: 0.95 }
}
}}
])
$sum – Counting and Totaling
Within a $group stage, $sum serves two purposes:
{ $sum: 1 }counts the Number of documents per group.{ $sum: "$field" }calculates the sum of a numeric field.
Collection orders:
{ _id: 1, customer: "A", amount: 150 }
{ _id: 2, customer: "B", amount: 200 }
{ _id: 3, customer: "A", amount: 100 }
To get the total spent and order count for each customer:
db.orders.aggregate([
{ $group: { _id: "$customer", totalSpent: { $sum: "$amount" }, orderCount: { $sum: 1 } } }
])
These operators form the backbone of everyday MongoDB work, from basic filtering to sophisticated analytical queries.