Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching string with special characters in MongoDB document

Tags:

I want to search values having special characters such as " $ / . @ > " in a document.

Lets consider, I've myKey with values like "test$australia", "test$austria", "test$belgium", "green.africa".

I want to search values with '.*$aus.*',

For example,

db.myCollection.find({ myKey : /.*$aus.*/i });  

OR

db.myCollection.find({ myKey : { '$regex' : '.*$aus.*','$options' : 'i' }); 

Above queries dont work , how should I form query? I'm using MongoDB 2.4.1.

like image 867
Dex Avatar asked May 15 '13 08:05

Dex


2 Answers

You have to escape $ by \:

db.myCollection.find({ myKey : /.*\$aus.*/i });  // OR db.myCollection.find({myKey: { $regex: '.*\\$aus.*', $options: 'i'}}) 
like image 81
Stephane Godbillon Avatar answered Oct 04 '22 03:10

Stephane Godbillon


You can use this:

db.myCollection.find({myKey:{ $regex:new RegExp('^' + 'test$australia'.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + '$', 'i')}}) 
like image 31
Arjun G Perambra Avatar answered Oct 04 '22 01:10

Arjun G Perambra