0

I have a problem in mongodb query. I have to fetch only those rows from table 'Feed' where field named 'message' having sub string 'you & me' or 'abc ? def'.

I am using following query but it is not working.

db.getCollection('Feed').find({"message": { "$regex" : 'you & me | abc ? def'}});

I got an alternate solution also for above by replacing all special character with its hexadecimal value like given below query.

db.getCollection('Feed').find({"message": { "$regex" : 'you \0x26 me | abc \0x3f def'}});

but in this case result is coming only for 'you \0x26 me' it means if i convert special character with hexadecimal value. it works only for first search regex.

1 Answer 1

2

You need to escape the & and ? in your regex because they are special character.

db.getCollection('Feed').find({ 'message': /\s*you \& me\s*|\s*abc \? def\s*/ })

Demo

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

2 Comments

In given link of demo, there is given in explanation that \s* matches any white space character. But in my case there may be any character before and after search keyword. what changes to be done for my requirement in the place of \s*.
it doesn't matter the regex will still work. just try it

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.