Unable to use $regex in mongoose in aggregation query? Unable to use $regex in mongoose in aggregation query? mongoose mongoose

Unable to use $regex in mongoose in aggregation query?


You can use regex in $match and you will get your result as in this example

Pincodes.aggregate([{ "$match": { "district": new RegExp('^' + req.query.district, "i") } },{ "$group": { "_id": "$district" } }]).exec((err, data) => {if (err) {res.status(500).json({data: err})}else {res.status(200).json({data: data})}})


Doing just agg.match({'<fieldName'>:new RegExp('^' + req.query.district, "i")}) didnt work for me

I had to use eval in the solution.if you are JSON.stringifying the aggregate query to see the output you won't see the effect of eval. Eval will have an effect later on when passed down to mongo.

agg.match({'<fieldName'>:eval(new RegExp('^' + req.query.district, "i"))});