ashish kumar gupta
ashish kumar gupta

Reputation: 31

MongoDB Regex with multiple string having special character

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.

Upvotes: 0

Views: 3000

Answers (1)

Sede
Sede

Reputation: 61273

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

Upvotes: 2

Related Questions