$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><expresson2>等)的数组执行逻辑AND操作,并选择满足所有表达式的文档。

Note注意

MongoDB provides an implicit AND operation when specifying a comma separated list of expressions.当指定逗号分隔的表达式列表时,MongoDB提供隐式AND操作。

Behavior行为

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 to false.在提供给$and的第一个表达式之后提供的表达式可能会导致错误,即使第一个表达式的计算结果为false

For example, the following query always produces an error if $x is 0:例如,如果$x0,以下查询始终会产生错误:

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的多个表达式,如果存在$x0的任何文档,则可能会产生错误:

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集合中的所有文档,其中:

  • the price field value is not equal to 1.99 andprice字段值不等于1.99,并且
  • the 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 } } )

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:查询将选择以下位置的所有文档:

  • the qty field value is less than 10 or greater than 50, andqty字段值小于10或大于50,并且
  • the sale field value is equal to true or the price field value is less than 5.sale字段值等于trueprice字段值小于5

The query cannot use an implicit AND operation because it uses the $or operator more than once.查询无法使用隐式AND操作,因为它多次使用$or运算符。

Tip提示
See also: 参阅:
←  Logical Query Operators$not →