Reputation: 373
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.
Upvotes: 33
Views: 98571
Reputation: 2343
Escape all regex special characters:
name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
Create a query with regex and option "i" (ignore case):
const databaseQuery = { name: new RegExp(`${req.query.name}`, 'i') };
Perform a search with a query:
db.collection.find(databaseQuery)
Note: don't forget to create indexes for the fields that you will search through. Indexing fields increases the speed of your regex queries. In my case for my 'name' field it would be like this:
db.collection.createIndex({ name: "text" })
Upvotes: 11
Reputation: 237
The Java Equivalent for https://stackoverflow.com/a/52322010/8208083 is as follows:
Pattern p = Pattern.compile("[\\.\\*\\+\\?\\^\\${}\\(\\)|\\]\\[\\\\]");
Matcher m = p.matcher(searchKeyword);
searchKeyword = m.replaceAll("\\\\$0");
This is useful when you need to pass the search keyword in the @Query annotation of Spring.
Upvotes: 2
Reputation: 41
Define the search key under the re.escape
function that will resolve the issue for special character regex.
{search_field: {"$regex": '{}.*'.format(re.escape(search_key)),"$options": 'i'}}
Upvotes: 0
Reputation: 485
You can use https://www.npmjs.com/package/regex-escape. It is a good library for escaping special characters to be used in regular expressions
var RegexEscape = require("regex-escape");
let keyword = RegexEscape("{#/}");
// => \{#\/\}
db.myCollection.find({ myKey : { '$regex' : keyword, '$options' : 'mi' });
Upvotes: 1
Reputation: 2284
You can use this:
db.myCollection.find({myKey:{ $regex:new RegExp('^' + 'test$australia'.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + '$', 'i')}})
Upvotes: 7
Reputation: 31
db.test.insert({word: 'hai('});
db.test.insert({word: 'jana'});
Output be like that :
{ "_id" : ObjectId("56f27fb71d843581261433c6"), "word" : "hai(" }
{ "_id" : ObjectId("56f27ffe1d843581261433c8"), "word" : "jana" }
Note : Want the special char row alone so
db.test.find({word:{$regex:"\\("}});
Output be like this:
{ "_id" : ObjectId("56f27fb71d843581261433c6"), "word" : "hai(" }
Upvotes: 3
Reputation: 1886
You have to escape $
by \
:
db.myCollection.find({ myKey : /.*\$aus.*/i });
// OR
db.myCollection.find({myKey: { $regex: '.*\\$aus.*', $options: 'i'}})
Upvotes: 32