【问题标题】:Aggregate where property minus property is bigger than value属性减去属性大于值的聚合
【发布时间】:2021-12-27 12:11:35
【问题描述】:

我尝试聚合 firstValue 减去 secondValue 大于 2 的文档

示例文件:

[
 {
   "firstValue": 6,
   "secondValue": 3
 },
 {
  "firstValue": 6,
  "secondValue": 5
 },
 {
  "firstValue": 6,
  "secondValue": 7
 }
]

查询应该只返回第一个元素 (6-3 = 3, 3>2)

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    您可以使用简单的查找:

    db.collection.find({
      "$expr": {
        $gt: [
          {
            "$subtract": [
              "$firstValue",
              "$secondValue"
            ]
          },
          2
        ]
      }
    })
    

    find fiddle

    或者使用这个表达式来聚合:

    db.collection.aggregate({
      "$match": {
        "$expr": {
          $gt: [
            {
              "$subtract": [
                "$firstValue",
                "$secondValue"
              ]
            },
            2
          ]
        }
      }
    })
    

    aggregate fiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-11
      • 2022-12-18
      • 2017-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-01
      相关资源
      最近更新 更多