在mongodb中使用Regex

Rah*_*ane 3 regex mongodb

我正在尝试在我的mongodb查询中使用正则表达式.根据文档,我可以在我的查询中运行正则表达式,如下所示:

db.customers.find( { name : /^foo.bar/ } );
Run Code Online (Sandbox Code Playgroud)

有没有办法在文档中存储正则表达式并检索正则表达式与提供的字符串匹配的文档?

示例文档:

{ _id : SomeID , matcher : "/^foo.bar/" }
Run Code Online (Sandbox Code Playgroud)

查询(在我的梦中).

db.customers.find( { matcher : { $matches : "foozbar" } );
Run Code Online (Sandbox Code Playgroud)

Vas*_*nov 6

是的,您可以在查询中使用任意JavaScript.

> db.customers.insert({_id: 9, matcher: '^foo.bar'})
> db.customers.insert({_id: 318, matcher: '^bar.qux'})
> db.customers.insert({_id: 44, matcher: '^foo[a-z]+r'})
> db.customers.find(function() {
...     return RegExp(this.matcher).test('foozbar');
... })
{ "_id" : 9, "matcher" : "^foo.bar" }
{ "_id" : 44, "matcher" : "^foo[a-z]+r" }
Run Code Online (Sandbox Code Playgroud)