【问题标题】:If field exist must be true, but if not exist must be pass like true如果字段存在必须为真,但如果不存在则必须像真一样通过
【发布时间】:2020-06-13 10:40:23
【问题描述】:

我想检查管道aggregate (existeTransformacion) 中是否存在字段。如果此字段存在必须为真才能通过($match),如果为假,我需要从结果中排除,但如果不存在则必须通过。我怎样才能做到这一点?

 {
            //...more data
            "ubicacionActual": {
                "transformacion": {
                   "trabajando": true,
                }
            },
            //This field come from $project in this way 
            //$project: {existeTransformacion: '$ubicacionActual.transformacion.trabajando'}
            "existeTransformacion": true,
            "paso": 1
        },

所以基本上:

  • 如果存在existeTransformacionexisteTransformacion===true 必须展示。

  • 如果存在existeTransformacionexisteTransformacion===false 一定没有显示。

  • 如果不存在,则必须显示。

【问题讨论】:

  • 有点迷惑:你已经有了existeTransformacion这个字段?或者你需要计算它的价值? $match 仅适用于管道步骤,不适用于 $project

标签: mongodb mongoose aggregate


【解决方案1】:

您需要使用$or$exists 运算符

{
  $match: {
    $or: [
      {
        "existeTransformacion": true
      },
      {
        "existeTransformacion": {
          $exists: false
        }
      }
    ]
  }
}

MongoPlayground

【讨论】:

    猜你喜欢
    • 2019-05-15
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 2020-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多