3

I'm trying to use regular expressions in my mongodb queries. According the documentation I can run a regular expression in my query like this :

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

But is there a way to store a regex in the document and retreive the documents where the regex matches a supplied string ?

Example document :

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

Query (in my dreams).

db.customers.find( { matcher : { $matches : "foozbar" } );
1
  • Howmany number of rows are there in your collection? I think this is not working with large number of row in collection. Commented Jul 25, 2012 at 12:19

1 Answer 1

6

Yes, you can use 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" }
Sign up to request clarification or add additional context in comments.

3 Comments

@Vasiliy-foronov This is working good for small number of rows in collection. But if I have 200k rows in collection, it is not working. I think there is a problem of timeout. Let me your suggestion.
@MaulikVora My answer runs JavaScript on MongoDB, which is slow. I don’t know if there is any other way to do this. Perhaps you could go the other way around: do you really need to match against plain, unrestricted regexes?
its like using $where query, it cannot use any indexing so it would be slow. I think it's as good as it gets.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.