2. MongoDB Operators
2.1 Comparison Operators
$eq – Equal to
Syntax: { field: { $eq: value } }
Example: db.collection.find({ age: { $eq: 25 } })
$ne – Not equal to
Syntax: { field: { $ne: value } }
Example: db.collection.find({ age: { $ne: 25 } })
$gt – Greater than
Syntax: { field: { $gt: value } }
Example: db.collection.find({ age: { $gt: 25 } })
$gte – Greater than or equal to
Syntax: { field: { $gte: value } }
Example: db.collection.find({ age: { $gte: 25 } })
$lt – Less than
Syntax: { field: { $lt: value } }
Example: db.collection.find({ age: { $lt: 25 } })
$lte – Less than or equal to
Syntax: { field: { $lte: value } }
Example: db.collection.find({ age: { $lte: 25 } })
2.2 Logical Operators
$and – Matches documents that satisfy all specified conditions
Syntax: { $and: [ { <condition1> }, { <condition2> } ] }
Example: db.collection.find({ $and: [{ age: { $gt: 25 } }, { name: "Alice" }] })
$or – Matches documents that satisfy at least one condition
Syntax: { $or: [ { <condition1> }, { <condition2> } ] }
Example: db.collection.find({ $or: [{ age: { $gt: 25 } }, { name: "Alice" }] })
$not – Inverts the effect of the query
Syntax: { field: { $not: { <operator-expression> } } }
Example: db.collection.find({ age: { $not: { $gt: 25 } } })
$nor – Matches documents that fail all conditions
Syntax: { $nor: [ { <condition1> }, { <condition2> } ] }
Example: db.collection.find({ $nor: [{ age: { $gt: 25 } }, { name: "Alice" }] })
2.3 Element Operators
$exists – Checks if a field exists
Syntax: { field: { $exists: true } }
Example: db.collection.find({ age: { $exists: true } })
$type – Checks the data type of a field
Syntax: { field: { $type: "int" } }
Example: db.collection.find({ age: { $type: "int" } })
2.4 Array Operators
$in – Matches values in an array
Syntax: { field: { $in: [25, 30, 35] } }
Example: db.collection.find({ age: { $in: [25, 30, 35] } })
$nin – Matches values not in an array
Syntax: { field: { $nin: [25, 30, 35] } }
Example: db.collection.find({ age: { $nin: [25, 30, 35] } })
0 Comments