MongoDb - MongoDB Operators

MongoDB Operators 

MongoDB operators are special keywords used in queries, updates, projections, and aggregations.
I’ll organize them into 7 main categories:


1. Comparison Operators

Used in queries to compare field values.

Operator Description Example
$eq Equal to { age: { $eq: 25 } } → Finds docs where age = 25
$ne Not equal to { status: { $ne: "active" } }
$gt Greater than { price: { $gt: 100 } }
$gte Greater than or equal { price: { $gte: 100 } }
$lt Less than { price: { $lt: 100 } }
$lte Less than or equal { price: { $lte: 100 } }
$in Matches any in array { status: { $in: ["active", "pending"] } }
$nin Not in array { status: { $nin: ["closed", "canceled"] } }

2. Logical Operators

Used to combine multiple conditions.

Operator Description Example
$and All conditions must match { $and: [ { age: { $gte: 18 } }, { age: { $lte: 30 } } ] }
$or At least one matches { $or: [ { status: "active" }, { points: { $gt: 100 } } ] }
$nor None of them match { $nor: [ { status: "active" }, { points: { $gt: 100 } } ] }
$not Negates condition { age: { $not: { $gt: 30 } } }

3. Element Operators

Used to check if a field exists or type.

Operator Description Example
$exists Checks if field exists { email: { $exists: true } }
$type Checks data type { age: { $type: "number" } }

4. Evaluation Operators

Used for pattern matching and expression evaluation.

Operator Description Example
$regex Regular expression search { name: { $regex: "^A" } } → Names starting with A
$expr Use aggregation expressions in queries { $expr: { $gt: ["$price", "$discountPrice"] } }
$mod Divisible by { qty: { $mod: [5, 0] } } → qty divisible by 5
$text Text search { $text: { $search: "mongodb" } }
$where Use JavaScript function { $where: "this.price > this.discount" }

5. Array Operators

Used to query and update array fields.

Operator Description Example
$all Matches all values in an array { tags: { $all: ["mongodb", "database"] } }
$elemMatch Matches documents with at least one array element matching multiple conditions { scores: { $elemMatch: { $gt: 80, $lt: 90 } } }
$size Matches arrays by length { tags: { $size: 3 } }
$push Add element to array { $push: { tags: "newTag" } }
$pop Remove first/last element { $pop: { tags: 1 } } → removes last
$pull Remove matching element { $pull: { tags: "oldTag" } }
$addToSet Adds only if not exists { $addToSet: { tags: "uniqueTag" } }

6. Update Operators

Used in updateOne(), updateMany(), etc.

Field Update

Operator Description Example
$set Set field value { $set: { status: "active" } }
$unset Remove field { $unset: { oldField: "" } }
$inc Increment number { $inc: { score: 5 } }
$mul Multiply number { $mul: { price: 1.1 } }
$rename Rename field { $rename: { oldName: "newName" } }
$currentDate Set current date { $currentDate: { updatedAt: true } }

7. Aggregation Operators

Used inside aggregate() pipelines.

Operator Description Example
$sum Sum values { $group: { _id: "$category", total: { $sum: "$amount" } } }
$avg Average { $group: { _id: "$category", avgPrice: { $avg: "$price" } } }
$min Minimum value { $group: { _id: "$category", minPrice: { $min: "$price" } } }
$max Maximum value { $group: { _id: "$category", maxPrice: { $max: "$price" } } }
$first First document in group { $group: { _id: "$category", firstItem: { $first: "$name" } } }
$last Last document in group { $group: { _id: "$category", lastItem: { $last: "$name" } } }
$concat Concatenate strings { $project: { fullName: { $concat: ["$firstName", " ", "$lastName"] } } }
$toUpper Convert to uppercase { $project: { upperName: { $toUpper: "$name" } } }
$toLower Convert to lowercase { $project: { lowerName: { $toLower: "$name" } } }
$dateToString Format date { $project: { dateStr: { $dateToString: { format: "%Y-%m-%d", date: "$createdAt" } } } }

8. Special Operators

Operator Description Example
$geoWithin Geo-spatial queries { location: { $geoWithin: { $centerSphere: [[lng, lat], radius] } } }
$near Find nearest points { location: { $near: { $geometry: {...}, $maxDistance: 500 } } }
$rand Random number (MongoDB 7+) { score: { $rand: {} } }

Summary

  • Comparison$eq, $gt, $in

  • Logical$and, $or, $not

  • Array$push, $size, $elemMatch

  • Update$set, $inc, $unset

  • Aggregation$sum, $avg, $concat

  • Special$geoWithin, $rand