5

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})
2
  • 4
    If you want regex then text search will be useless to you (for multiple reasons), you want to delove to normal querying. Commented May 25, 2014 at 13:20
  • @Sammaye That being rectified, can I search multiple regex terms as a string.Basically I am trying to pass this query term from the client side itself to reduce the string building process on the server. Commented May 25, 2014 at 13:37

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

3 Comments

How can I add multiple regex terms to this. Like /1234/ OR /5678/
okay, So I did figure it out. Thanks. /1234|5678/ would be it!
If the keywords contain only numbers and letters that will work.

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.