【问题标题】:Remove null MongoDB aggregation删除空 MongoDB 聚合
【发布时间】:2021-01-26 00:58:30
【问题描述】:

如果该字段为空,我只想留空。

数据:

"history": [{
        "status": "Not Processed",
        "createdAt": {
            "$date": "2021-01-26T00:16:26.018Z"
        },
        "updatedAt": {
            "$date": "2021-01-26T00:16:26.018Z"
        }
    }, {
        "status": "Processed",
        "updatedAt": {
            "$date": "2021-01-26T00:17:25.725Z"
        },
        "createdAt": {
            "$date": "2021-01-26T00:17:25.725Z"
        }
    }],

输入:

{
  "$reduce": {
      "input": "$history",
      "initialValue": null,
      "in": {
          "$cond": {
              "if": {
                  $eq: [
                      "$$this.status",
                      "Processed"
                  ]
              },
              "then": "$$this.createdAt",
              "else": "$$value"
          }
      }
  }
}

我的一些数据在历史数组中没有已处理状态。我不想在我的数据中包含 null。 FYR:我在 mongodb 图表中执行此操作。

【问题讨论】:

  • 在其中添加一个和条件怎么样。
  • ` "and": { $ifNull: ["$$this.status", "Accepted", null] } `这是在else之后的正确位置吗?

标签: mongodb mongodb-query aggregation-framework mongodb-charts


【解决方案1】:

Play

您可以在 if 语句的条件中使用布尔表达式。

db.collection.aggregate([
  {
    $project: {
      "res": {
        "$reduce": {
          "input": "$history",
          "initialValue": null,
          "in": {
            "$cond": {
              "if": {
                $and: [
                  {
                    $eq: [
                      "$$this.status",
                      "Processed"
                    ]
                  },
                  {
                    $ne: [
                      "$$this.status",
                      null
                    ]
                  }
                ]
              },
              "then": "$$this.createdAt",
              "else": "$$value"
            }
          }
        }
      }
    }
  }
])

【讨论】:

  • 您好,我尝试输出“无数据”,但它不起作用。它仍然显示为空。
  • 你在操场上检查了吗?可以加个游乐场吗?在我的示例中,我评论了状态。
  • 嗨,在 Res:我想放一个“无数据”,但这是不可能的,因为如果我把它放在初始值中,它会输出一个错误 cant $subtract adate从字符串
  • 哦。为此,您可以添加另一个项目阶段。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-23
  • 1970-01-01
  • 2020-07-02
  • 2019-09-21
  • 2016-08-10
  • 1970-01-01
  • 2016-05-27
相关资源
最近更新 更多