$and
On this page本页内容
$and-
Syntax:
{ $and: [ { <expression1> }, { <expression2> } , ... , { <expressionN> } ] }$andperforms a logical对一个或多个表达式(ANDoperation 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在指定以逗号分隔的表达式列表时提供了一个隐含的ANDoperation 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如果提供给$andwould cause an error when evaluated alone, the$andcontaining the expression may cause an error but an error is not guaranteed.$and的任何表达式在单独计算时会导致错误,则包含该表达式的$and可能会导致错误但不能保证会出错。An expression supplied after the first expression supplied to在提供给$andmay 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集合中的所有文档,其中:
thepricefield value is not equal to1.99andprice字段值不等于1.99,并且thepricefield 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:查询将选择所有文档,其中:
theqtyfield value is less than10or greater than50, andqty字段值小于10或大于50,以及thesalefield value is equal totrueor thepricefield 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运算符。