$and

On this page本页内容

$and

Syntax: { $and: [ { <expression1> }, { <expression2> } , ... , { <expressionN> } ] }

$and performs a logical AND operation on an array of one or more expressions (e.g. <expression1>, <expression2>, etc.) and selects the documents that satisfy all the expressions in the array. 对一个或多个表达式(例如<expression1><expression2>)的数组执行逻辑“与”运算,并选择满足数组中所有表达式的文档。The $and operator uses short-circuit evaluation. $and运算符使用短路评估。If the first expression (e.g. <expression1>) evaluates to false, MongoDB will not evaluate the remaining expressions.如果第一个表达式(例如<expression1>)的计算结果为false,MongoDB将不会计算其余表达式。

Note

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

Examples示例

AND Queries With Multiple Expressions Specifying the Same Field使用多个表达式指定同一字段的查询

Consider the following example:考虑下面的例子:

db.inventory.find( { $and: [ { price: { $ne: 1.99 } }, { price: { $exists: true } } ] } )

This query will select 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字段存在。

This query can be also be constructed with an implicit AND operation by combining the operator expressions for the price field. 也可以通过组合price字段的运算符表达式,使用隐式AND操作构造此查询。For example, this query can be written as:例如,此查询可以编写为:

db.inventory.find( { price: { $ne: 1.99, $exists: true } } )

AND Queries With Multiple Expressions Specifying the Same Operator使用多个表达式指定同一运算符的查询

Consider the following example:考虑下面的例子:

db.inventory.find( {
    $and: [
        { $or: [ { qty: { $lt : 10 } }, { qty : { $gt: 50 } } ] },
        { $or: [ { sale: true }, { price : { $lt : 5 } } ] }
    ]
} )

This query will select 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

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

See also参阅

find(), update(), $ne, $exists, $set.