Searching string with special characters in MongoD

2019-01-14 22:57发布

问题:

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.

回答1:

You have to escape $ by \:

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


回答2:

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(" }


回答3:

You can use this:

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


回答4:

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


标签: mongodb