【问题标题】:Using Regex in mongodb在 mongodb 中使用正则表达式
【发布时间】:2011-11-30 22:15:27
【问题描述】:

我正在尝试在我的 mongodb 查询中使用正则表达式。 根据文档,我可以像这样在查询中运行正则表达式:

db.customers.find( { name : /^foo.bar/ } );

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

示例文档:

{ _id : SomeID , matcher : "/^foo.bar/" }

查询(在我的梦中)。

db.customers.find( { matcher : { $matches : "foozbar" } );

【问题讨论】:

  • 您的集合中有多少行?我认为这不适用于集合中的大量行。

标签: regex mongodb


【解决方案1】:

是的,您可以使用arbitrary JavaScript in queries

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

【讨论】:

  • @Vasiliy-foronov 这适用于集合中的少量行。但是,如果我收集了 200k 行,它就不起作用。我认为存在超时问题。告诉我你的建议。
  • @MaulikVora 我的答案在 MongoDB 上运行 JavaScript,速度很慢。我不知道是否还有其他方法可以做到这一点。也许你可以反过来:你真的需要匹配普通的、不受限制的正则表达式吗?
  • 它就像使用 $where 查询一样,它不能使用任何索引,所以它会很慢。我认为它和它一样好。
猜你喜欢
  • 1970-01-01
  • 2020-09-14
  • 1970-01-01
  • 2017-01-18
  • 1970-01-01
  • 2022-07-28
  • 2016-03-02
  • 2014-01-26
相关资源
最近更新 更多