33

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.

7 Answers 7

32

You have to escape $ by \:

db.myCollection.find({ myKey : /.*\$aus.*/i }); 
// OR
db.myCollection.find({myKey: { $regex: '.*\\$aus.*', $options: 'i'}})
4
  • Could you please remove qr operator which is not needed in console.. I edited in the question also. It did worked.
    – Dex
    May 15, 2013 at 9:22
  • Also how can I achieve the same with REGEX option.
    – Dex
    May 15, 2013 at 9:38
  • 2
    You have to double the backslash in the regex string in the mongo json query: db.myCollection.find({myKey: { $regex: '.*\\$aus.*', $options: 'i'}}) May 15, 2013 at 9:45
  • db.mycollection_name.find({ "name" : { "$regex" : "Corp Limited \\( Group\\)", "$options" : "i" }},{name:1}) Worked for me
    – GoutamS
    May 31, 2022 at 17:54
11

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" })
0
7

You can use this:

db.myCollection.find({myKey:{ $regex:new RegExp('^' + 'test$australia'.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + '$', 'i')}})
3
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(" }
1

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' });
1

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.

0

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'}}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.