On this page
$and (aggregation)
在本页面
Definition
$and
- 计算一个或多个表达式,如果所有表达式都是
true
或如果没有参数表达式则被唤醒,则返回true
。否则,$and返回false
。
- 计算一个或多个表达式,如果所有表达式都是
$and具有以下语法:
{ $and: [ <expression1>, <expression2>, ... ] }
有关表达式的更多信息,请参见Expressions。
Behavior
$and使用短路逻辑:遇到第一个false
表达式后,该操作停止求值。
除了false
布尔值外,$and还将以下值评估为false
:null
,0
和undefined
值。 $and会将所有其他值评估为true
,包括非零数值和数组。
Example | Result | |
---|---|---|
{ $and: [ 1, "green" ] } |
true |
|
{ $and: [ ] } |
true |
|
{ $and: [ [ null ], [ false ], [ 0 ] ] } |
true |
|
{ $and: [ null, true ] } |
false |
|
{ $and: [ 0, true ] } |
false |
Example
使用以下文档创建示例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 }