【问题标题】:Unable to use $regex in mongoose in aggregation query?在聚合查询中无法在 mongoose 中使用 $regex?
【发布时间】:2016-11-12 04:13:53
【问题描述】:

在 mongoose 聚合查询中使用 $regex 时出现错误。我得到一个无效的运算符,错误号为 15999。请大家帮忙。

{ $match: { "_id": ObjectId(req.headers.token) } }, {
                        $project: {
                            inventory: {
                                $filter: {
                                    input: '$inventory',
                                    as: 'inventory',
                                    cond: {$or:[{"$$inventory.item":new RegExp('^'+req.query.text+'$', "i")},{"$$inventory.sku":new RegExp('^'+req.query.text+'$', "i")}]}
                                }
                            },
                            _id: 0
             }
  }

【问题讨论】:

  • 你可以将 req.query.text 视为字符串
  • 如果可以使用 JS 代码,请尝试将其转义为 req.query.text.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')。如果文本包含 [( 或其他特殊的正则表达式元字符,这应该可以解决问题。
  • 不确定是否可以在 $project stackoverflow.com/questions/29866336/… 中使用正则表达式

标签: regex node.js mongodb express mongoose


【解决方案1】:

您可以在 $match 中使用正则表达式,您将得到如本例所示的结果

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
})
}
})

【讨论】:

    【解决方案2】:

    只做agg.match({'<fieldName'>:new RegExp('^' + req.query.district, "i")}) 对我没用

    我不得不在解决方案中使用 eval。 如果您正在 JSON.stringifying 聚合查询以查看输出,您将看不到 eval 的效果。 eval 将在稍后传递给 mongo 时产生影响。

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

    【讨论】:

      猜你喜欢
      • 2016-10-20
      • 2017-10-19
      • 1970-01-01
      • 1970-01-01
      • 2013-04-21
      • 1970-01-01
      • 2012-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多