Skip to main content

operators

Operators in MongoDB

MongoDB offers a variety of operators that help in querying, updating, and manipulating data. Below are key categories and commonly used operators:


1. Query Operators

Used to filter documents in queries (find(), findOne()).

OperatorDescriptionExample Query
$eqEquals{ age: { $eq: 21 } }
$neNot equals{ age: { $ne: 21 } }
$gtGreater than{ age: { $gt: 18 } }
$gteGreater or equal{ age: { $gte: 18 } }
$ltLess than{ age: { $lt: 18 } }
$lteLess or equal{ age: { $lte: 18 } }
$inMatches any value{ major: { $in: ["Physics", "Biology"] } }
$ninNot in list{ major: { $nin: ["Math", "History"] } }

2. Logical Operators

Used to combine query conditions.

OperatorDescriptionExample Query
$andLogical AND{ $and: [ { age: { $gt: 18 } }, { major: "Physics" } ] }
$orLogical OR{ $or: [ { major: "Physics" }, { major: "Math" } ] }
$notNegates condition{ age: { $not: { $lt: 18 } } }
$norLogical NOR{ $nor: [ { major: "Physics" }, { age: { $gt: 21 } } ] }

3. Update Operators

Used to modify fields in documents.

OperatorDescriptionExample Query
$setUpdates a field{ $set: { age: 22 } }
$unsetRemoves a field{ $unset: { major: "" } }
$incIncrements a value{ $inc: { age: 1 } }
$mulMultiplies a value{ $mul: { age: 2 } }
$renameRenames a field{ $rename: { "oldField": "newField" } }
$pushAdds to an array{ $push: { courses: "Biology" } }
$popRemoves from array{ $pop: { courses: -1 } }
$pullRemoves by value{ $pull: { courses: "Physics" } }

4. Array Operators

Used for querying and updating arrays.

OperatorDescriptionExample Query
$allMatches all values in an array{ courses: { $all: ["Physics", "Math"] } }
$elemMatchMatches array element{ courses: { $elemMatch: { score: { $gt: 90 } } } }
$sizeMatches array size{ courses: { $size: 3 } }

5. Element Operators

Used to match fields based on their existence or type.

OperatorDescriptionExample Query
$existsField existence{ major: { $exists: true } }
$typeMatches data type{ age: { $type: "int" } }

6. Aggregation Operators

Used within aggregation pipelines.

OperatorDescriptionExample
$sumCalculates sum{ $sum: "$amount" }
$avgCalculates average{ $avg: "$score" }
$maxFinds maximum{ $max: "$score" }
$minFinds minimum{ $min: "$score" }

7. Comparison Operators in Aggregation

Used in aggregation queries.

OperatorDescriptionExample
$eqEquals{ $eq: ["$age", 21] }
$gtGreater than{ $gt: ["$age", 18] }

Summary

  • Query operators filter data ($eq, $gt, $in).
  • Logical operators combine multiple conditions ($and, $or).
  • Update operators modify data ($set, $push).
  • Array and aggregation operators handle more complex data structures.

Let me know if you want more practical examples or clarifications! 😊