Home > Blockchain >  Execlude certain values in the group stage in mongodb
Execlude certain values in the group stage in mongodb

Time:01-29

In my code i am trying to collect the available filters however there are fields that were not filled by the user and left as empty strings e.g the "brands" field. however, empty strings should not be considered as a valid value

this is my group stage:

{
    $group: {
        _id: null,
        sizes: { $addToSet: '$combinations.size' },
        colors: { $push: '$combinations.color' },
        brands: { $addToSet: '$brand' },
        topPrice: { $max: `$price.${req.query.reg || 'aud'}` },
        bottomPrice: { $min: `$price.${req.query.reg || 'aud'}` },
    },
},

the brands field will be: [ "" ]

what i wanted is []

CodePudding user response:

You can use conditional aggregating.

db.collection.aggregate([
  {
    $group: {
      "_id": null,
      "brands": {
        "$addToSet": {
          $cond: [
            {$eq: ["$brand",""]},  //if brands is empty string,
            "$$REMOVE",            //then, REMOVE it
            "$brand"               //else, keep it
          ]
        }
      }
    }
  }
])

Demo

  • Related