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>、<expresson2>等)的数组执行逻辑AND操作,并选择满足所有表达式的文档。
MongoDB provides an implicit 当指定逗号分隔的表达式列表时,MongoDB提供隐式AND operation when specifying a comma separated list of expressions.AND操作。
To allow the query engine to optimize queries, 要允许查询引擎优化查询,$and handles errors as follows:and按如下方式处理错误:
$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可能会导致错误但不保证会出现错误。$and may cause an error even if the first expression evaluates to false.$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 ] } }
]
} )
ANDConsider this query:考虑以下查询:
db.inventory.find( { $and: [ { price: { $ne: 1.99 } }, { price: { $exists: true } } ] } )
The query selects all documents in the 查询将选择inventory collection where:inventory集合中的所有文档,其中:
price field value is not equal to 1.99 andprice字段值不等于1.99,并且price 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 } } )
ANDConsider 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:查询将选择以下位置的所有文档:
qty field value is less than 10 or greater than 50, andqty字段值小于10或大于50,并且sale field value is equal to true or the price field value is less than 5.sale字段值等于true或price字段值小于5。The query cannot use an implicit 查询无法使用隐式AND operation because it uses the $or operator more than once.AND操作,因为它多次使用$or运算符。