首页 > 解决方案 > $match 中的 Mongo 聚合条件查询

问题描述

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

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

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

标签: mongodbaggregation-framework

解决方案


Query1
(没有聚合运算符)

测试代码在这里

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

Query2
(与您的查询类似的聚合运算符)

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

测试代码在这里

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

推荐阅读