7

I have a document in MongoDB with a regex attribute

    {
        _id: ObjectId("516023189732da20ce000004"),
        regex: /^(my|your)\s+regex$/
    }

and I need to retrieve this document with something like db.col.find({regex: 'your regex'}) and db.col.find({regex: 'my regex'}). In MySQL I'd do: SELECT * FROM table WHERE 'my regex' REGEXP table.regex. How can I achieve this in MongoDB?

4
  • hnmm maybe I am missing something but doesn't: db.col.find({regex: '/^[my|your]\s+regex$/'}) work since it isn't outisde of quotes and it isn't a regexp object? Commented Apr 12, 2013 at 9:01
  • This seems to be a perl(ish) regex. This means this will not match to my regex or your regex, but m regex or y regex or | regex &c. If it had to match with my regex it would be /^(my|your)\s+regex$/. Am I missing something? Commented Apr 12, 2013 at 9:11
  • @TrueY you're right, I used the wrong parenthesis. Commented Apr 12, 2013 at 9:14
  • @Sammaye I need to match a string against a regex object attribute. Commented Apr 12, 2013 at 9:21

2 Answers 2

11

You can use the $where operator in the following fashion:

db.col.find({$where: "\"my regex\".match(this.regex)"})
Sign up to request clarification or add additional context in comments.

3 Comments

Although pretty slow, it works, thank you! But it matches also documents where this.regex is not defined, so I think I'm going to define a function instead of the expression.
I'm afraid that using $where is always slow, MongoDB documentation discourages using it... I also would like to know about quicker ways :) Of course, you can use a JavaScript function for the $where value to deal with edge cases such as not defined fields, etc.
BTW a ticket is opened in MongoDB JIRA about this improvement jira.mongodb.org/browse/SERVER-13902
7

As explained into Jira ticket provided by @fgalan on 2013, you can use $expr you can use this query:

db.collection.find({
  "$expr": {
    "$regexMatch": {
      "input": "$key",
      "regex": "$regex",
      "options": "i"
    }
  }
})

Example here

With $expr you can avoid $where which is not efficient.

1 Comment

Is there any kind of index to satisfy and speed up this query?

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.