How to check if the $unwind field is null?

How so I check if the unwind field is null?

[
{
$lookup: {
....,
as: "user"

},
{
$unwind: {
path: "$user",
preserveNullAndEmptyArrays: true
}
},
{
$project: {
isValid: {
$cond: [{$eq: ["$user", null], '123', 'abc']
}
}
}
]

The example above is just to print 123 is the unwinded $user is null / undefined / does not exist, and ‘abc’ is if it exists. (it’s an example, as the MongoDB always returns ‘123’).

I have also tried $cond: [ {'user': {exitst: true}}, true, false] and it didn’t work, always returned true alsoe

I do not have an answer to your specific question. But a way to do what I think you want to do is compute isValid before $unwind using a $set stage and the $size of the array. Something like:

set_stage = { "$set" : {
    "isValid" : { "$ne" : [ { "$size" : "$user"} , 0 ] }
} }
2 Likes

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