Query operators (comparison, logical, element, array, bitwise, etc.)
MongoDB provides a rich set of query operators for performing various operations when querying documents. These operators can be categorized into comparison, logical, element, array, bitwise, and other types, each with specific purposes and syntax.
Comparison Operators
Comparison operators are used to compare field values with specified values. Common comparison operators include:
$eq
: Matches fields equal to the specified value$ne
: Matches fields not equal to the specified value$gt
: Matches fields greater than the specified value$gte
: Matches fields greater than or equal to the specified value$lt
: Matches fields less than the specified value$lte
: Matches fields less than or equal to the specified value$in
: Matches fields that contain any value in the specified array$nin
: Matches fields that do not contain any value in the specified array
// Find users older than 25
db.users.find({ age: { $gt: 25 } })
// Find users with status "active" or "pending"
db.users.find({ status: { $in: ["active", "pending"] } })
Logical Operators
Logical operators are used to combine multiple query conditions for complex logical evaluations. Key logical operators include:
$and
: Logical AND, all conditions must be satisfied$or
: Logical OR, at least one condition must be satisfied$not
: Logical NOT, inverts the query condition$nor
: Logical NOR, none of the conditions must be satisfied
// Find users older than 25 AND with status "active"
db.users.find({
$and: [
{ age: { $gt: 25 } },
{ status: "active" }
]
})
// Find users younger than 20 OR older than 30
db.users.find({
$or: [
{ age: { $lt: 20 } },
{ age: { $gt: 30 } }
]
})
Element Operators
Element operators check for the existence or data type of fields in documents:
$exists
: Checks if a field exists$type
: Checks the BSON type of a field
// Find users with an email field
db.users.find({ email: { $exists: true } })
// Find users where the age field is of number type
db.users.find({ age: { $type: "number" } })
Array Operators
Array operators are specialized for handling array fields:
$all
: Matches arrays containing all specified elements$elemMatch
: Matches arrays where at least one element satisfies all specified conditions$size
: Matches arrays of the specified length
// Find users whose skills array includes both "JavaScript" and "MongoDB"
db.users.find({ skills: { $all: ["JavaScript", "MongoDB"] } })
// Find users with at least one score greater than 90 in the "math" course
db.users.find({
scores: {
$elemMatch: {
score: { $gt: 90 },
course: "math"
}
}
})
Bitwise Operators
Bitwise operators perform bit-level operations on integer values:
$bitsAllSet
: Matches fields where all specified bits are set to 1$bitsAnySet
: Matches fields where any specified bit is set to 1$bitsAllClear
: Matches fields where all specified bits are cleared to 0$bitsAnyClear
: Matches fields where any specified bit is cleared to 0
// Find documents where bits 1 and 3 of the flags field are set to 1
db.users.find({ flags: { $bitsAllSet: [1, 3] } })
// Find documents where bits 2 or 4 of the permissions field are set to 1
db.users.find({ permissions: { $bitsAnySet: [2, 4] } })
Evaluation Operators
Evaluation operators allow the use of JavaScript expressions or other evaluation methods in queries:
$expr
: Enables the use of aggregation expressions in query language$jsonSchema
: Validates documents against a given JSON schema$mod
: Performs modulo operation on field values and matches the result$regex
: Provides regular expression matching for strings$text
: Performs text search
// Compare two fields using an expression
db.sales.find({
$expr: {
$gt: ["$revenue", "$cost"]
}
})
// Match names starting with "John" using a regular expression
db.users.find({ name: { $regex: /^John/ } })
Geospatial Operators
MongoDB provides specialized geospatial query operators:
$geoWithin
: Matches geospatial data entirely within a specified geometry$geoIntersects
: Matches geospatial data that intersects with a specified geometry$near
: Returns documents near a specified point, sorted by distance$nearSphere
: Similar to $near but uses spherical geometry for distance calculation
// Find locations within a specified polygon
db.places.find({
location: {
$geoWithin: {
$geometry: {
type: "Polygon",
coordinates: [[[0,0], [3,6], [6,0], [0,0]]]
}
}
}
})
Projection Operators
Projection operators control which fields are returned in queries:
$
: Projects the first element in an array that matches the query condition$elemMatch
: Projects the first element in an array that matches specified conditions$meta
: Projects text search scores or other metadata$slice
: Limits the number of array elements returned
// Return only the first matching comment from the comments array
db.posts.find(
{ "comments.author": "John" },
{ "comments.$": 1 }
)
// Return the first 3 elements of the scores array
db.students.find(
{},
{ scores: { $slice: 3 } }
)
Update Operators
Though primarily used for updates, these operators also have special uses in query contexts:
$
: Acts as a placeholder to update the first array element matching the query$[]
: Acts as a placeholder to update all array elements matching the query$[<identifier>]
: Used with arrayFilters to update array elements matching specified conditions
// Update the first order with status "pending"
db.orders.update(
{ "items.status": "pending" },
{ $set: { "items.$.status": "processing" } }
)
Aggregation Pipeline Operators
Special query operators used in aggregation pipelines:
$match
: Filters documents, similar to find()$lookup
: Performs a left outer join$graphLookup
: Performs a recursive search$redact
: Restricts document content based on field values
// Using $match in an aggregation pipeline
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: { _id: "$customer", total: { $sum: "$amount" } } }
])
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:批量操作(bulkWrite)