Database Manual / Reference / Query Language / Query Predicates / Logical

$and

$and

$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.$and对一个或多个表达式(<expression1><expression2>等)的数组执行逻辑AND运算,并选择满足所有表达式的文档。

Note

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

Compatibility兼容性

You can use $and for deployments hosted in the following environments:您可以将$and用于在以下环境中托管的部署:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Syntax语法

The $and has the following syntax:$and具有以下语法:

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

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 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 ] } }
]
} )

Most programming languages and drivers, including the MongoDB Shell (mongosh), do not allow the construction of objects with duplicate keys at the same object level. For example, consider this query:大多数编程语言和驱动程序,包括MongoDB Shellmongosh),都不允许在同一对象级别构造具有重复键的对象。例如,考虑以下查询:

db.inventory.find( { price: { $in: [ 7.99, 3.99 ], $in: [ 4.99, 1.99 ] } } )

The above query does not construct correctly because the field name price has duplicate operators at the same object level. As a result, the query sent to the server differs from what is intended. For the query to work as expected, use an explicit AND operator:上述查询构造不正确,因为字段名price在同一对象级别有重复的运算符。因此,发送到服务器的查询与预期不同。为了使查询按预期工作,请使用显式的AND运算符:

db.inventory.find( {
$and: [
{ price: { $in: [ 7.99, 3.99 ] } },
{ price: { $in: [ 4.99, 1.99 ] } }
]
} )

This query explicitly checks that both conditions are satisfied: the price array must include at least one value from each $in set. 此查询显式检查是否满足这两个条件:price数组必须至少包含每个$in集中一个值。For more information on how to address such scenarios, see the Examples section.有关如何解决此类情况的更多信息,请参阅示例部分。

Examples示例

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

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字段存在。

You can simplify this query by combining the operator expressions for the price field into a single query object with a nested implicit AND:您可以通过将price字段的运算符表达式组合到一个具有嵌套隐式AND的查询对象中来简化此查询:

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

Sometimes such rewrites are not possible, particularly when dealing with duplicate conditions on the same field. For example:有时这种重写是不可能的,特别是在处理同一字段上的重复条件时。例如:

db.inventory.find( { status: { $ne: "closed", $ne: "archived" } } )

The above query does not construct correctly because it uses the $ne operator more than once on the same status field name at the same object level. 上述查询构造不正确,因为它在同一对象级别的同一status字段名称上多次使用$ne运算符。In this case, the $nin operator provides a more effective solution:在这种情况下,$nin运算符提供了一种更有效的解决方案:

db.inventory.find( { status: { $nin: [ "closed", "archived" ] } } )

How you rewrite a query depends on the intended semantics of your use case. Consider the following query:如何重写查询取决于用例的预期语义。考虑以下查询:

db.inventory.find( {
$and: [
{ status: "new" },
{ status: "processing" }
]
} )

If you want to find documents where status is either new or processing, you can use the $in operator:如果您想查找statusnewprocessing的文档,可以使用$in运算符:

db.inventory.find( { status: { $in: [ "new", "processing" ] } } )

If your status field is an array [ "new", "processing" ], and you want to check if the document contains both the new and processing values, use the $all operator:如果status字段是一个数组[ "new", "processing" ],并且您想检查文档是否同时包含newprocessing值,请使用$all运算符:

db.inventory.find( { status: { $all: [ "new", "processing" ] } } )

In this context, this query is semantically equivalent to AND, but $all is often clearer when querying array fields.在这种情况下,此查询在语义上等同于AND,但在查询数组字段时,$all通常更清晰。

Similar to duplicate field names, the same considerations apply for duplicate operators used in the query.与重复的字段名类似,同样的注意事项也适用于查询中使用的重复运算符。