我想用SQL查询一些东西,比如查询:

SELECT * FROM users  WHERE name LIKE '%m%'

如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。


当前回答

如果使用Node.js,它表示您可以编写以下内容:

db.collection.find( { field: /acme.*corp/i } );

// Or
db.collection.find( { field: { $regex: 'acme.*corp', $options: 'i' } } );

此外,您还可以这样写:

db.collection.find( { field: new RegExp('acme.*corp', 'i') } );

其他回答

可以使用正则表达式进行查询:

db.users.find({"name": /m/});

如果字符串来自用户,则可能需要在使用该字符串之前对其进行转义。这将防止来自用户的文字字符被解释为正则表达式标记。

例如,如果不转义,搜索字符串“A”也将匹配“AB”。在使用字符串之前,可以使用一个简单的替换来转义字符串

function textLike(str) {
  var escaped = str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
  return new RegExp(escaped, 'i');
}

所以现在,字符串变成了一个不区分大小写的模式,同时匹配文字点。例子:

>  textLike('A.');
<  /A\./i

现在,我们可以随时生成正则表达式了:

db.users.find({ "name": textLike("m") });

将模板文字与变量一起使用也有效:

{“firstname”:{$regex:`^${req.body.firstname}.*`,$options:'si'}}

您可以在MongoDB中使用正则表达式。

例如

db.users.find({"name": /^m/})

字符串yourdb={deepakparmar,dipak,parmar}

db.getCollection('yourdb').find({"name":/^dee/})

ans deepakparmar公司

db.getCollection('yourdb').find({"name":/d/})

ans deepakparmar,迪帕克

db.getCollection('yourdb').find({"name":/mar$/})

ans deepakparmar,帕尔马

正则表达式的处理成本很高。

另一种方法是创建文本索引,然后使用$search进行搜索。

创建要搜索的字段的文本索引:

db.collection.createIndex({name: 'text', otherField: 'text'});

在文本索引中搜索字符串:

db.collection.find({
  '$text'=>{'$search': "The string"}
})