Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

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.

question from:https://stackoverflow.com/questions/65894505/remove-null-mongodb-aggregation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...