$and
On this page本页内容
$and
-
Syntax:
{ $and: [ { <expression1> }, { <expression2> } , ... , { <expressionN> } ] }
$and
performs a logical对一个或多个表达式(AND
operation on an array of one or more expressions (<expression1>
,<expression2>
, and so on) and selects the documents that satisfy all the expressions.<expression1>
、<expression2>
等)的数组执行逻辑AND
运算,并选择满足所有表达式的文档。NoteMongoDB provides an implicitMongoDB在指定以逗号分隔的表达式列表时提供了一个隐含的AND
operation when specifying a comma separated list of expressions.AND
操作。
Behavior行为
When evaluating the clauses in the 在评估$and
expression, MongoDB's query optimizer considers which indexes are available that could help satisfy clauses of the $and
expression when selecting the best plan to execute.$and
表达式中的子句时,MongoDB的查询优化器会在选择执行的最佳计划时考虑哪些索引可以帮助满足$and
表达式的子句。
To allow the query engine to optimize queries, 为了允许查询引擎优化查询,$and
handles errors as follows:$and
按如下方式处理错误:
If any expression supplied to如果提供给$and
would cause an error when evaluated alone, the$and
containing the expression may cause an error but an error is not guaranteed.$and
的任何表达式在单独计算时会导致错误,则包含该表达式的$and
可能会导致错误但不能保证会出错。An expression supplied after the first expression supplied to在提供给$and
may cause an error even if the first expression evaluates tofalse
.$and
的第一个表达式之后提供的表达式,即使第一个表达式的计算结果为false
,也可能导致错误。
For example, the following query always produces an error if 例如,如果$x
is 0
:$x
为0
,则以下查询总是会产生错误:
db.example.find( {
$expr: { $eq: [ { $divide: [ 1, "$x" ] }, 3 ] }
} )
The following query, which contains multiple expressions supplied to 以下查询包含提供给$and
, may produce an error if there is any document where $x
is 0
:$and
的多个表达式,如果存在$x
为0
的任何文档,则可能会产生错误:
db.example.find( {
$and: [
{ x: { $ne: 0 } },
{ $expr: { $eq: [ { $divide: [ 1, "$x" ] }, 3 ] } }
]
} )
Examples实例
AND
Queries With Multiple Expressions Specifying the Same Field具有指定同一字段的多个表达式的查询
Consider this query:请考虑以下查询:
db.inventory.find( { $and: [ { price: { $ne: 1.99 } }, { price: { $exists: true } } ] } )
The query selects all documents in the 查询选择inventory
collection where:inventory
集合中的所有文档,其中:
theprice
field value is not equal to1.99
andprice
字段值不等于1.99
,并且theprice
field exists.price
字段存在。
The query can be rewritten with an implicit 可以使用隐式AND
operation that combines the operator expressions for the price
field:AND
运算重写查询,该运算组合了price
字段的运算符表达式:
db.inventory.find( { price: { $ne: 1.99, $exists: true } } )
AND
Queries With Multiple Expressions Specifying the Same Operator具有指定同一运算符的多个表达式的查询
Consider this query:请考虑以下查询:
db.inventory.find( {
$and: [
{ $or: [ { qty: { $lt : 10 } }, { qty : { $gt: 50 } } ] },
{ $or: [ { sale: true }, { price : { $lt : 5 } } ] }
]
} )
The query selects all documents where:查询将选择所有文档,其中:
theqty
field value is less than10
or greater than50
, andqty
字段值小于10
或大于50
,以及thesale
field value is equal totrue
or theprice
field value is less than5
.sale
字段值等于true
或者price
字段值小于5
。
The query cannot use an implicit 查询不能使用隐式AND
operation because it uses the $or
operator more than once.AND
运算,因为它多次使用$or
运算符。