【问题标题】:Mongo Aggregate Conditional query within $match$match内的Mongodb聚合条件查询
【发布时间】:2021-10-01 16:41:30
【问题描述】:

基本上,如果一个字段存在,我想运行一个查询,否则,我想运行一个单独的。

`db.Collection.aggregate([
    {
        $match: {
            $cond: [{if fieldOnCollection:{$exists:true}}, {fieldOnCollection:'foo'}, {anotherField:'bar'}]
        }
    }
]);`

我只见过$cond 用于其他阶段,而不是构建由集合本身的字段组成的查询的实际部分

【问题讨论】:

  • 什么是 foo?驱动程序变量(例如 javascript 变量)?还是必须在数据库中计算的值?(例如mongodb字段或变量$$var
  • 对不清楚的地方表示歉意。 foo 应该只代表 $cond 的通用布尔值。但是我更新了帖子。布尔值本身用于是否存在特定字段

标签: mongodb aggregation-framework


【解决方案1】:

查询1
(没有聚合运算符)

Test code here

db.collection.aggregate({
  "$match": {
    "$or": [
      {
        "fieldOnCollection": "foo"
      },
      {
        "$and": [
          {
            "fieldOnCollection": {
              "$exists": false
            }
          },
          {
            "anotherField": "bar"
          }
        ]
      }
    ]
  }
})

查询2
(使用与您的查询类似的聚合运算符)

  • 如果字段存在,测试它是否与“foo”相等
  • else 检查其他字段是否等于“bar”

Test code here

db.collection.aggregate([
  {
    "$match": {
      "$expr": {
        "$cond": [
          {
            "$ne": [
              {
                "$type": "$fieldOnCollection"
              },
              "missing"
            ]
          },
          {
            "$eq": [
              "$fieldOnCollection",
              "foo"
            ]
          },
          {
            "$eq": [
              "$anotherField",
              "bar"
            ]
          }
        ]
      }
    }
  }
])

【讨论】:

    【解决方案2】:

    不清楚,你试图实现什么。无论如何,你的语法是错误的。应该是这样的:

    { $cond: [
       { $ne : ["$fieldOnCollection", undefined] }, 
       'foo', 
       'bar'
       ]
    }
    

    { $cond: {
       if: { $ne : ["$fieldOnCollection", undefined] }, 
       then: 'foo', 
       else: 'bar'
       }
    }
    

    如果您需要检查某个字段是否存在,请参阅https://stackoverflow.com/a/68255564/3027266

    【讨论】:

      猜你喜欢
      • 2020-09-22
      • 2020-08-06
      • 2013-04-21
      • 1970-01-01
      • 2021-01-11
      • 2021-05-04
      • 1970-01-01
      • 2019-03-25
      • 2017-02-22
      相关资源
      最近更新 更多