Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a regex with text search in MongoDB

I have created a text index on the num field in the collection. Now while passing the string to search from the text index, I need to use a regex which has to be passed as a string to the $search variable.

My current query works fine but it doesn't work when I add a regex to it.

Current Query:

db.collection.find({$text:{$search:"1234 6789"}},{'id':1})

I need to add a regex/like query to the $search to make it something like

db.collection.find({$text:{$search:"/1234/ /6789/"}},{'id':1})

where I get all the values from the database that contain a pattern like "1234" OR "6789".

I did try the query but it gives me a $search needs a String error:

db.collection.find({$text:{$search:/1234/}},{'id':1})
like image 734
Rohit Minni Avatar asked May 25 '14 13:05

Rohit Minni


1 Answers

To achieve this you should use the $regex MongoDB operator:

// Without options
db.collection.find({num: /1234|5678/i});

// Separate options property
db.collection.find({num: {$regex: /1234|5678/, $options: 'i'}});

To add multiple terms in the regex, use the | operator

$regex docs and examples

Edit:

For querying records using an array of values the $in operator can be used:

$in docs and examples

like image 96
Catalin MUNTEANU Avatar answered Oct 12 '22 13:10

Catalin MUNTEANU