Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if sub-field exists and is not null in mongodb aggregation?

I got quite an annoying problem, and I can't seem to find any solution for my specific case. In my mongo agggregation pipeline, I'd like to add a field, and depending on the existence of another field's subfield, I'd like to assign the value of that other field's subfield, or 1 if that other field's subfield does not exist.

Here is what I tried:

pipelineStages.push(
{$addFields: 
    {field: 
        {$cond: [
             {$ne: ["$otherField.subField", null]}, 
                    "$otherField.subField", 1]
             }
        }
     }
 );

However, it only works fine for the case that the field exists. In the other, that new field is not added to the pipeline at all. Any ideas what I'm doing wrong?

like image 589
Michał Szydłowski Avatar asked Mar 23 '17 15:03

Michał Szydłowski


3 Answers

Wrapping $ifNull in $cond does the trick, even with the subfield problem.

pipelineStages.push({
    $addFields: {
        newField: {
            $cond: [
                { 
                    "$ifNull": [ 
                        "$otherField.subField", 
                        false 
                    ] 
                },
                "$otherField.subField",
                1
            ]
        }
     }
 );
like image 169
Johann8 Avatar answered Sep 19 '22 13:09

Johann8


To check if the field exists and is not null, use:

pipelineStages.push({ 
  $addFields: {
    field: {
      $cond: [
        {"$gt": [$otherField, null]}, "$otherField.subField", 1
      ]
    }
  }
})

On the contrary, to check if the field doesn't exist or is null, use:

{"$lte": [$otherField, null]}
like image 44
Ricky Boyce Avatar answered Sep 20 '22 13:09

Ricky Boyce


Did you try this version of condition:

pipelineStages.push({ $addFields: 
    {field: 
        {$cond: [{$and: [{"$otherField": {"$exists": true}}, {"$otherField.subField": {"$exists": true}}]}, "$otherField.subField", 1]
        }
    }
 });
like image 28
Vitalii Andrusishyn Avatar answered Sep 21 '22 13:09

Vitalii Andrusishyn