AliveSquare
AliveSquare

Reputation: 37

Is it possible to default a value in Mongodb like $ifNull but with empty string?

A mongo operator I love to use is $ifNull, but sometimes this doesn't cover all the cases I need to cover, like for example an empty string. Is there an operator that works like the $ifNull operator (but with other conditions getting checked, like empty string), all in a single step? I just need to default the value if it's null or empty string. Below is a snippet of a query I'm doing currently:

//ex docs:
{
  "_id": "1",
  "field": {
    "value": "test"
  }
},
{
  "_id": "2",
  "field": {
    "value": ""
  }
},
{
  "_id": "3"
  "field": {
    "value": null
  }
}
//step in query where I'm checking ifNull:
...
{
    $project: {
        resValue: {
            $ifNull: ["$field.value", "No Data"]
        },
    }
}
...

I'm trying to google around but see a lot of solutions involving $function, or just matching out the results with empty strings. This doesn't work in my case because I need all the documents included, but just need to default the resValue to "No Data" if it's empty or null. I'm also trying to limit the complexity and keep the query as efficient as possible, so I figure it's best not to include a $function step before the project.

Currently running version 4.4.13 on my db.

I need to return the value of the field itself if it exists and isn't an empty string, but if it's empty string or null, return "No Data" or some other default string as resValue on the resultant doc.

Upvotes: 2

Views: 7530

Answers (1)

ray
ray

Reputation: 15227

You are already on the right track of using $ifNull. You just need one more $cond to check for empty string case.

db.collection.aggregate([
  {
    "$addFields": {
      "resValue": {
        "$cond": {
          "if": {
            $eq: [
              {
                "$ifNull": [
                  "$field.value",
                  ""
                ]
              },
              ""
            ]
          },
          "then": "No Data",
          "else": "$field.value"
        }
      }
    }
  }
])

Here is the Mongo playground for your reference.

Upvotes: 2

Related Questions