Search code examples
mongodbmongodb-queryaggregation-frameworkmongodb-charts

Remove null MongoDB aggregation


I want to just put blank if the field is null.

Data:

"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"
        }
    }],

Input:

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

Some of my data doesn't have a processed status in history array. I do not want to include null in my data. FYR: I'm doing this in mongodb charts.


Solution

  • Play

    You can use boolean expressions in the condition of if statement.

    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"
                }
              }
            }
          }
        }
      }
    ])