Mongodb – aggregation $push if conditional

You can use "$$REMOVE":

  • This system variable was added in version 3.6 (mongodb docs)
db.collection.aggregate([{
   $group:{
       field: {
          $push: {
              $cond:[
                { $gt: ["$A", 0] },
                { id: "$_id", A:"$A" },
                "$$REMOVE"
            ]
          }
        },
        secondField:{ $push: "$B" }
    }
])

In this way you don’t have to filter nulls.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)