Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB reverse regex

Tags:

regex

mongodb

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?

like image 903
Giovanni Lovato Avatar asked Apr 12 '13 08:04

Giovanni Lovato


2 Answers

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

db.col.find({$where: "\"my regex\".match(this.regex)"})
like image 186
fgalan Avatar answered Sep 18 '22 00:09

fgalan


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.

like image 43
J.F. Avatar answered Sep 19 '22 00:09

J.F.