“文档” 菜单
文档首页
/
MongoDB Manual
/ / /

$and(聚合)

在此页面上

  • 定义
  • 行为
  • 错误处理
  • 例子
$and

计算一个或多个表达式,如果所有表达式均为true或在无参数表达式的情况下运行,则返回true 。否则, $and返回false

$and 事务语法:

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

有关表达式的更多信息,请参阅表达式。

除了 false 布尔值外,$and 还将以下值计算为 falsenull0undefined 值。$and 将所有其他值(包括非零数值和数组)计算为 true

例子
结果
{ $and: [ 1, "green" ] }
true
{ $and: [ ] }
true
{ $and: [ [ null ], [ false ], [ 0 ] ] }
true
{ $and: [ null, true ] }
false
{ $and: [ 0, true ] }
false

要允许查询引擎优化查询,$and 会按如下方式处理错误:

  • 如果提供给 $and 的任何表达式在单独求值时会导致错误,则包含该表达式的 $and 可能但不一定会导致错误。

  • 在提供给 $and 的第一个表达式之后提供的表达式可能会导致错误,即使第一个表达式的计算结果为 false

例如,如果 $x0,以下查询会始终产生错误:

db.example.find( {
$expr: { $eq: [ { $divide: [ 1, "$x" ] }, 3 ] }
} )

以下查询包含提供给 $and 的多个表达式,如果存在 $x0 的任何文档,则查询可能会产生错误:

db.example.find( {
$and: [
{ x: { $ne: 0 } },
{ $expr: { $eq: [ { $divide: [ 1, "$x" ] }, 3 ] } }
]
} )

用这些文档创建示例 inventory 集合:

db.inventory.insertMany([
{ "_id" : 1, "item" : "abc1", description: "product 1", qty: 300 },
{ "_id" : 2, "item" : "abc2", description: "product 2", qty: 200 },
{ "_id" : 3, "item" : "xyz1", description: "product 3", qty: 250 },
{ "_id" : 4, "item" : "VWZ1", description: "product 4", qty: 300 },
{ "_id" : 5, "item" : "VWZ2", description: "product 5", qty: 180 }
])

此操作使用 $and 运算符来确定 qty 是否大于 100 小于 250

db.inventory.aggregate(
[
{
$project:
{
item: 1,
qty: 1,
result: { $and: [ { $gt: [ "$qty", 100 ] }, { $lt: [ "$qty", 250 ] } ] }
}
}
]
)

操作会返回这些结果:

{ "_id" : 1, "item" : "abc1", "qty" : 300, "result" : false }
{ "_id" : 2, "item" : "abc2", "qty" : 200, "result" : true }
{ "_id" : 3, "item" : "xyz1", "qty" : 250, "result" : false }
{ "_id" : 4, "item" : "VWZ1", "qty" : 300, "result" : false }
{ "_id" : 5, "item" : "VWZ2", "qty" : 180, "result" : true }
← $allElementsTrue(聚合)