$addfields with $cond is not working

Hello, I am trying to use $cond inside $addFields to add a field if not exists.

I have tried the attached playground so you can see that I cannot make it work

Any help will be appreciated

Thanks

I had it working like this:

db.getCollection("Test").aggregate([
{
    $addFields:{
        assignee2:{
            $cond:{
                if:{$gt:['$assignee', null]},
                then:'$assignee',
                else:{}
            }
        }        
    }
}
])

You could also use $ifNull:

db.getCollection("Test").aggregate([
{
    $addFields:{
        assignee2:{
            $ifNull:[
                '$assignee',
                {}
            ]
        }        
    }
}
])

There is a similar post here:

2 Likes

Thanks a lot John, it worked

Hi @Yannis_Ragkavas, Welcome back,

I respect the answer of @John_Sewell, just need to add more insight to your question and also for others.

Why is $cond + $eq +null not working on a non-existent field?

In MongoDB, While the field is missing, it’s not considered null, instead, it simply doesn’t exist or it has an undefined value.

You just need to understand the data type and value of the property and which operator is useful for your use case.

→ Your condition will be fulfilled if you check undefined instead of null in the $eq operator, but make sure that if some of the documents are null in your collection then again this condition will be wrong.

→ You can check the data type of the property by the $type operator, in your case it will return the "missing" type, but again If the field exists and has a null value then it will return the "null" type.

→ However, if want to check both conditions null and undefined together then the best option is the $ifNull operator as John suggested in the previous post.

2 Likes

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