Searching string with special characters in MongoDB document

Escape all regex special characters:

  req.query.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" })

You can use this:

db.myCollection.find({myKey:{ $regex:new RegExp('^' + 'test$australia'.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + '$', 'i')}})

You have to escape $ by \:

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

Tags:

Mongodb