在MongoDB文档中搜索带有特殊字符的字符串

dex*_*dex 18 mongodb

我想搜索具有特殊字符的值,例如" $ / . @ > "在文档中.

让我们考虑一下,我的myKey值是这样的 "test$australia", "test$austria", "test$belgium", "green.africa".

我想搜索值 '.*$aus.*',

例如,

db.myCollection.find({ myKey : /.*$aus.*/i }); 
Run Code Online (Sandbox Code Playgroud)

要么

db.myCollection.find({ myKey : { '$regex' : '.*$aus.*','$options' : 'i' });
Run Code Online (Sandbox Code Playgroud)

以上查询不起作用,我应该如何形成查询?我正在使用MongoDB 2.4.1.

Ste*_*lon 17

你要逃避$\:

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

  • 您必须在 mongo json 查询中的正则表达式字符串中加倍反斜杠: `db.myCollection.find({myKey: { $regex: '.*\\$aus.*', $options: 'i'}}) ` (2认同)

Hil*_*hka 10

转义所有正则表达式特殊字符:

  name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
Run Code Online (Sandbox Code Playgroud)

使用正则表达式和选项“i”创建查询(忽略大小写):

  const databaseQuery = { name: new RegExp(`${req.query.name}`, 'i') };
Run Code Online (Sandbox Code Playgroud)

使用查询执行搜索:

  db.collection.find(databaseQuery)
Run Code Online (Sandbox Code Playgroud)

注意:不要忘记为您将搜索的字段创建索引。索引字段可以提高正则表达式查询的速度。就我而言,我的“姓名”字段将是这样的:

  db.collection.createIndex({ name: "text" })
Run Code Online (Sandbox Code Playgroud)


Arj*_*bra 5

你可以使用这个:

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