Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to avoid $push-ing nulls in mongo aggregation framework

$push is aggregating nulls if the field is not present. I would like to avoid this.

Is there a way to make a sub expression for $push operator in such way that null values will be skipped and not pushed into the resulting array ?

like image 357
Ivan Davidov Avatar asked Mar 15 '15 19:03

Ivan Davidov


1 Answers

Bit late to the party, but..

I wanted to do the same thing, and found that I could accomplish it with an expression like this:

  // Pushes events only if they have the value 'A'
  "events": {
    "$push": {
      "$cond": [
        {
          "$eq": [
            "$event",
            "A"
          ]
        },
        "A",
        "$noval"
      ]
    }
  }

The thinking here is that when you do

{ "$push": "$event" } 

then it seems to only push non-null values.

So I made up a column that doesn't exist, $noval, to be returned as the false condition of my $cond.

It seems to work. I'm not sure if it is non-standard and therefore susceptible to breaking one day but..

like image 174
user384842 Avatar answered Sep 27 '22 18:09

user384842