$and (aggregation)

    在本页面

    $and

    计算一个或多个表达式,如果所有表达式都为true,或者如果没有参数表达式调用,则返回true。否则,$and返回false

    $and 具有以下语法:

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

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

    行为

    $and使用短路逻辑:遇到第一个false表达式后,运算将停止评估。

    除了false布尔值,$and计算为false如下:null0,和undefined 的值。在$and评估所有其它值true,包括非零数值和阵列。

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

    例子

    inventory使用以下文档创建示例集合:

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

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

    1. db.inventory.aggregate(
    2. [
    3. {
    4. $project:
    5. {
    6. item: 1,
    7. qty: 1,
    8. result: { $and: [ { $gt: [ "$qty", 100 ] }, { $lt: [ "$qty", 250 ] } ] }
    9. }
    10. }
    11. ]
    12. )

    该操作返回以下结果:

    1. { "_id" : 1, "item" : "abc1", "qty" : 300, "result" : false }
    2. { "_id" : 2, "item" : "abc2", "qty" : 200, "result" : true }
    3. { "_id" : 3, "item" : "xyz1", "qty" : 250, "result" : false }
    4. { "_id" : 4, "item" : "VWZ1", "qty" : 300, "result" : false }
    5. { "_id" : 5, "item" : "VWZ2", "qty" : 180, "result" : true }

    译者:李冠飞

    校对: