Skip to main content

Read Operators

MongoDB provides a rich set of query operators that can be used in both find() and findOne() methods to filter and manipulate the data you're querying. Here's a detailed list of different types of operators:

Comparison Operators

In MongoDB, comparison operators are used to compare values in queries. These operators allow you to perform various types of comparisons, such as equality, inequality, and range-based comparisons. Here's a detailed look at the commonly used comparison operators:

Equality: $eq

The $eq operator matches values that are equal to a specified value.

db.collection.find({ field: { $eq: value } })

Not Equal: $ne

The $ne operator matches all values that are not equal to the specified value.

db.collection.find({ field: { $ne: value } })

Greater Than: $gt

The $gt operator matches values that are greater than the specified value.

db.collection.find({ field: { $gt: value } })

Greater Than or Equal: $gte

The $gte operator matches values that are greater than or equal to the specified value.

db.collection.find({ field: { $gte: value } })

Less Than: $lt

The $lt operator matches values that are less than the specified value.

db.collection.find({ field: { $lt: value } })

Less Than or Equal: $lte

The $lte operator matches values that are less than or equal to the specified value.

db.collection.find({ field: { $lte: value } })

In: $in

The $in operator matches any of the values specified in an array.

db.collection.find({ field: { $in: [value1, value2, ...] } })

Not In: $nin

The $nin operator matches none of the values specified in an array.

db.collection.find({ field: { $nin: [value1, value2, ...] } })

Exists: $exists

The $exists operator matches documents that have the specified field.

db.collection.find({ field: { $exists: true } })

Type: $type

The $type operator matches documents where the field is of the specified BSON type.

db.collection.find({ field: { $type: "string" } })

Modulus: $mod

The $mod operator performs a modulo operation on the value of a field and selects documents with a specified result.

db.collection.find({ field: { $mod: [divisor, remainder] } })

Regular Expression: $regex

The $regex operator provides regular expression capabilities for pattern matching strings in queries.

db.collection.find({ field: { $regex: /pattern/, $options: 'i' } })

All: $all

The $all operator matches arrays that contain all elements specified in the query.

db.collection.find({ field: { $all: [value1, value2, ...] } })

Element Match: $elemMatch

The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.

db.collection.find({ field: { $elemMatch: { field1: value1, field2: value2, ... } } })

Logical Operators

In MongoDB, logical operators are used to combine multiple query conditions. These operators allow you to perform complex queries by joining conditions, negating query statements, or evaluating multiple conditions. Here's a detailed look at commonly used logical operators:

$and

The $and operator joins multiple query clauses with a logical AND and returns all documents that satisfy all the conditions.

Syntax:

db.collection.find({ $and: [{ condition1 }, { condition2 }, ...] })

Example:

db.users.find({ $and: [{ age: { $gt: 21 } }, { status: "active" }] })

$or

The $or operator joins multiple query clauses with a logical OR and returns all documents that satisfy at least one of the conditions.

Syntax:

db.collection.find({ $or: [{ condition1 }, { condition2 }, ...] })

Example:

db.users.find({ $or: [{ age: { $lt: 30 } }, { status: "active" }] })

$not

The $not operator negates the effect of a query expression and returns documents that do not match the query expression.

Syntax:

db.collection.find({ field: { $not: { condition } } })

Example:

db.users.find({ age: { $not: { $lt: 30 } } })

$nor

The $nor operator joins multiple query clauses with a logical NOR and returns all documents that fail all the conditions.

Syntax:

db.collection.find({ $nor: [{ condition1 }, { condition2 }, ...] })

Example:

db.users.find({ $nor: [{ age: { $lt: 30 } }, { status: "inactive" }] })

$exists

While not strictly a logical operator, $exists is often used in logical operations to check the existence of a field.

Syntax:

db.collection.find({ field: { $exists: true|false } })

Example:

db.users.find({ email: { $exists: true } })

Combining Logical Operators

You can combine multiple logical operators to create more complex queries.

Example:

db.users.find({
$and: [
{ $or: [{ age: { $gt: 21 } }, { status: "active" }] },
{ email: { $exists: true } }
]
})

This query will return all users who are either over 21 or have an "active" status, and who also have an email address.

Array Operators

In MongoDB, array operators provide powerful ways to manipulate and query arrays within documents. These operators allow you to perform various types of operations, such as element matching, array projection, and array modification. Here's a detailed look at commonly used array operators:

Query Operators for Arrays

$all

The $all operator matches arrays that contain all elements specified in the query.

db.collection.find({ field: { $all: [value1, value2, ...] } })

$elemMatch

The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.

db.collection.find({ field: { $elemMatch: { field1: value1, field2: value2, ... } } })

$size

The $size operator matches any array with the number of elements specified.

db.collection.find({ field: { $size: size } })

Update Operators for Arrays

$push

The $push operator appends a specified value to an array.

db.collection.update({ query }, { $push: { field: value } })

$pop

The $pop operator removes the first or last element of an array. Pass -1 to remove the first element and 1 to remove the last element.

db.collection.update({ query }, { $pop: { field: 1 } })  // Removes last element

$pull

The $pull operator removes all instances of a value from an existing array.

db.collection.update({ query }, { $pull: { field: value } })

$addToSet

The $addToSet operator adds a value to an array only if it does not already exist.

db.collection.update({ query }, { $addToSet: { field: value } })

$pullAll

The $pullAll operator removes all matching values from an existing array.

db.collection.update({ query }, { $pullAll: { field: [value1, value2, ...] } })

Array Projection Operators

$slice

The $slice operator limits the number of elements projected from an array. Use it in the find() method's projection parameter.

db.collection.find({ query }, { field: { $slice: number } })

$

The $ operator projects the first element in an array that matches the query condition.

db.collection.find({ "array.field": value }, { "array.$": 1 })

Evaluation Operators

In MongoDB, evaluation operators are used to perform various types of data comparisons and evaluations within queries. These operators are particularly useful for pattern matching, array size evaluation, and other specialized query operations. Here's a detailed look at commonly used evaluation operators:

$regex

The $regex operator allows you to perform regular expression pattern matching against string fields.

Syntax:

db.collection.find({ field: { $regex: /pattern/, $options: 'i' } })

Example:

db.users.find({ name: { $regex: /^Jo/, $options: 'i' } })

$mod

The $mod operator performs a modulo operation on the value of a field and selects documents with a specified result.

Syntax:

db.collection.find({ field: { $mod: [divisor, remainder] } })

Example:

db.users.find({ age: { $mod: [10, 0] } })  // Finds users whose age is a multiple of 10

$text

The $text operator performs a text search on the content of the fields indexed with a text index.

Syntax:

db.collection.find({ $text: { $search: "string" } })

Example:

db.articles.find({ $text: { $search: "mongodb" } })

$where

The $where operator allows you to execute JavaScript code on the server for each document to determine if it should be included in the result set. Use this operator cautiously, as it can impact performance.

Syntax:

db.collection.find({ $where: "JavaScript_expression" })

Example:

db.users.find({ $where: "this.age > 30 && this.status === 'active'" })

$expr

The $expr operator allows you to use aggregation expression operators within the query language.

Syntax:

db.collection.find({ $expr: { $gt: ["$field1", "$field2"] } })

Example:

db.orders.find({ $expr: { $gt: ["$total", "$discount"] } })

$jsonSchema

The $jsonSchema operator allows you to validate documents against the given JSON Schema.

Syntax:

db.collection.find({ $jsonSchema: { /* JSON Schema */ } })

Example:

db.users.find({
$jsonSchema: {
properties: {
name: {
type: "string"
},
age: {
type: "number"
}
},
required: ["name", "age"]
}
})

Geospatial Operators

Geospatial operators in MongoDB allow you to perform queries based on geographic location, which is particularly useful for location-based services. These operators work with GeoJSON objects or legacy coordinate pairs to enable various types of geospatial queries. Here's a detailed look at commonly used geospatial operators:

$geoWithin

The $geoWithin operator selects documents with geospatial shapes that exist entirely within a specified shape.

Syntax:

db.collection.find({ location: { $geoWithin: { $geometry: { type, coordinates } } } })

Example:

db.places.find({
location: {
$geoWithin: {
$geometry: {
type: "Polygon",
coordinates: [[ [0, 0], [3, 6], [6, 1], [0, 0] ]]
}
}
}
})

$geoIntersects

The $geoIntersects operator selects documents whose geospatial data intersects with a specified GeoJSON object.

Syntax:

db.collection.find({ location: { $geoIntersects: { $geometry: { type, coordinates } } } })

Example:

db.places.find({
location: {
$geoIntersects: {
$geometry: {
type: "Point",
coordinates: [2, 2]
}
}
}
})

$near

The $near operator returns documents sorted by distance from a particular point, starting with the closest.

Syntax:

db.collection.find({ location: { $near: { $geometry: { type, coordinates }, $maxDistance: distance } } })

Example:

db.places.find({
location: {
$near: {
$geometry: {
type: "Point",
coordinates: [1, 1]
},
$maxDistance: 1000
}
}
})

$nearSphere

The $nearSphere operator is similar to $near but calculates distances using spherical geometry.

Syntax:

db.collection.find({ location: { $nearSphere: { $geometry: { type, coordinates }, $maxDistance: distance } } })

Example:

db.places.find({
location: {
$nearSphere: {
$geometry: {
type: "Point",
coordinates: [1, 1]
},
$maxDistance: 1000
}
}
})

$geoWithin with $center and $box

For legacy coordinate pairs, you can use $geoWithin with $center or $box to perform basic circular or rectangular queries.

Syntax for $center:

db.collection.find({ location: { $geoWithin: { $center: [[x, y], radius] } } })

Syntax for $box:

db.collection.find({ location: { $geoWithin: { $box: [[x1, y1], [x2, y2]] } } })