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})
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With