How to trim and match in a MongoDB aggregation?

Viewed 275

I want to do a MongoDB aggregation which first matches with some values and then groups them. But the field which has to be matched has values in the DB which have leading and trailing spaces in some of them. I want to first trim and then match them. How do I do that?

async AggregateTypes(_, { retailer_type }) {
  const matchCond = {};
  if(retailer_type) matchCond.cidm_retailer_type = {$in: retailer_type}
  res = await collection.aggregate([
    { 
        $match: matchCond 
    },
  ]);
}
1 Answers

You can try $trim operator in $expr expression match condition,

if(retailer_type) {
  matchCond = { 
    $expr: { 
      $in: [
        { $trim: { input: "$cidm_retailer_type" } }, 
        retailer_type
      ] 
    }
  }
}
Related