$project fields with null value during aggregation pipeline

Hi all, I want to omit the fields which have null value during $project step. Do you have any idea?

$project doesn’t filter. You need to filter out nulls in a $match stage.

Thanks for your response, however, I want to filter the null fields, not an entire document; with &match I will lose the related documents and its fields all.

I don’t follow. Can you give an example of what you’re trying to achieve?

In the meantime, suggest you look into $ne and $exists.

During the aggregation pipeline I would have some documents like this:
[{f1 : ‘some value’, f2: ‘value’},{f1: ‘other value’, f2: null}]
for target documents I want to project them as follow:
[{f1: ‘some value’, f2: ‘value’ (if it is not null, and in case of null just omitting this field)}]

That’s clear now. Using your example, here’s how:

db.collection.aggregate([
   {
      $project: {
         _id: 0, 
         f1: 1, 
         f2: {
            $cond: {
               if: {$eq: ["$f2", null]}, 
               then: "$$REMOVE", 
               else: "$f2" 
            }
         }
      }
   }
]).pretty()
3 Likes

Thank you Dude
That works!

You’re welcome!

Fyi, here’s a less verbose alternative of writing the $cond statement:
f2: {$cond: [{ $eq: ["$f2", null] }, "$$REMOVE", "$f2"]

1 Like