【问题标题】:MongoDB $cond with embedded document array带有嵌入式文档数组的 MongoDB $cond
【发布时间】:2020-04-09 19:17:43
【问题描述】:

我正在尝试生成一个新集合,其中包含一个字段“desc”,并考虑了文档数组中字段中的条件。为此,我使用 $cond 语句

origin collection示例是下一个:

{
        "_id" : ObjectId("5e8ef9a23e4f255bb41b9b40"),
        "Brand" : {
                "models" : [
                        {
                                "name" : "AA"
                        },
                        {
                                "name" : "BB"
                        }
                ]
        }
}
{
        "_id" : ObjectId("5e8ef9a83e4f255bb41b9b41"),
        "Brand" : {
                "models" : [
                        {
                                "name" : "AG"
                        },
                        {
                                "name" : "AA"
                        }
                ]
        }
}

查询是下一个:

db.runCommand({
    aggregate: 'cars',
    'pipeline': [
        {
            '$project': {
                'desc': {
                    '$cond': {
                        if: {
                            $in: ['$Brand.models.name',['BB','TC','TS']]
                        },
                        then: 'Good',
                        else: 'Bad'
                    }
                }
            }
        },
        {
            '$project': {
                'desc': 1
            }
        },
        {
            $out: 'cars_stg'
        }
    ],
    'allowDiskUse': true,
})

问题在于 $cond 语句总是返回“else”值。我也尝试过 $or 语句与 $eq$and$ne,但总是返回“其他”。

我做错了什么,或者我应该如何解决这个问题?

谢谢

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    由于$Brand.models.name返回一个数组,我们不能使用$in操作符。

    相反,我们可以使用$setIntersection,它返回一个数组,其中包含出现在每个输入数组中的元素

    db.cars.aggregate([
      {
        "$project": {
          "desc": {
            "$cond": [
              {
                $gt: [
                  {
                    $size: {
                      $setIntersection: [
                        "$Brand.models.name",
                        [
                          "BB",
                          "TC",
                          "TS"
                        ]
                      ]
                    }
                  },
                  0
                ]
              },
              "Good",
              "Bad"
            ]
          }
        }
      },
      {
        "$project": {
          "desc": 1
        }
      },
      {
          $out: 'cars_stg'
      }
    ])
    

    MongoPlayground | Alternative $reduce

    【讨论】:

      猜你喜欢
      • 2011-02-15
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-06
      • 2017-07-31
      相关资源
      最近更新 更多