$ifNull returning an array when the last value is a string

Hi Please help me understand this following.

"authors": {
  "$ifNull": ["$authors", ["$author"], "unspecified"]
}

Here in the $project, I have authors field and have used $ifNull for returning the values. The problem I faced is if authors and author both fields are empty. I want to return a string whose value is unspecified. But instead, I am getting an array with first value as null. Why?

The issue I believe is that your second parameter is being interpreted as not null, it’s defined as an array with null in it so passes the test and is returned.

You need another $ifnull in there to build the second option out a bit more:

db.getCollection("test").aggregate([
{
    $project:{
        "authors": {
          "$ifNull": [
             "$authors",
             [
                 {
                      $ifNull:["$author", "unspecified"]   
                 }
             ]
          ]
        }
    }
}
])
3 Likes

After researching and experimenting, I found the cause of this behaviour. When using $ifNull , it checks if authors exists. If the authors field is null or missing, it fills an array with author , but if author is empty, it returns an empty array. So, the ‘unspecified’ part is never reached.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.