正则表达式与 mongoose/mongoDB 上的 $where 一起使用



我正在尝试使用mongoose ORM从mongoDB中提取结果。下面的代码部分运行良好,并返回了"Test"的完全匹配项

db.getCollection('cards').find({
    $where: "this.name=='Test'"
})

我实际上想拉出"测试"的不区分大小写的匹配项。

下面一个工作,

db.getCollection('cards').find({"name":/test/i})

但我想在$where上使用正则表达式,如下所示,

db.getCollection('cards').find({
    $where: "this.name=='/Test/i'"
})

有人可以就如何在$where中解决正则表达式提出一些说明或方向吗?

db.getCollection('cards').find({"name": /Test/i})

上面的查询将为您提供包含"test"的任何名称

如果您想使用 $where 进行搜索

使用这个:

db.getCollection('cards').find({ $where: "/Test/.test(this.name)" })

恕我直言,您可以使用$regex本身。

{ <field>: { $regex: /pattern/, $options: '<options>' } }

例:

db.getCollection('cards').find({ name: { $regex: /Test/, $options: 'i' } })

最新更新