【问题标题】:How to use $lt and $gte without a common range?如何在没有共同范围的情况下使用 $lt 和 $gte?
【发布时间】:2021-04-26 11:43:28
【问题描述】:

如果我想得到大于 7 ($gte: 7) 或小于 3 ($lt: 3) 的客户的 response_due,使用 $match 聚合时我的查询应该是什么样子?

我试图做这样的事情:

db.customers.aggregation({$match: {response_due : {$gte: 7, $lt: 3}}})

但当然它没有用。 另外,我尝试做这样的事情:

db.customers.aggregation({$match: {$or: [ { $gt: [ "$response_due", 7 ] }, { $lt: [ "$response_due", 3 ] } ] }})

但它也没有工作。

解决方案和最佳方法是什么?

P.S:我为 NodeJS 使用原生 MongoDB 驱动程序。

【问题讨论】:

    标签: javascript node.js mongodb mongodb-query aggregation-framework


    【解决方案1】:

    db.customers.aggregation({$match: {$or: [ { $gt: [ "$response_due", 7 ] }, { $lt: [ "$response_due", 3 ] } ] }})

    您使用了$gt$lt的表达式语法,当您在$or运算符之前添加$expr运算符时,它将支持,

    db.customers.aggregation([
      {
        $match: {
          $expr: {
            $or: [
              { $gt: [ "$response_due", 7 ] }, 
              { $lt: [ "$response_due", 3 ] } 
            ] 
          }
        }
      }
    ])
    

    但原来你必须不用$gt$lt运算符的表达式匹配条件,指定字段名和单独的条件运算符,

    db.customers.aggregation([
      {
        $match: {
          $or: [
            { response_due: { $gte: 7 } },
            { response_due: { $lt: 3 } }
          ]
        }
      }
    ])
    

    【讨论】:

    • 非常感谢!它就像一个魅力!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 2022-10-18
    • 2021-10-29
    • 1970-01-01
    相关资源
    最近更新 更多