我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
当前回答
MongoRegex已被弃用。
使用MongoDB \ BSON \ Regex:
$regex = new MongoDB\BSON\Regex ( '^m');
$cursor = $collection->find(array('users' => $regex));
//iterate through the cursor
其他回答
似乎有理由同时使用JavaScript/regex_pattern/模式和MongoDB{“$regex”:“regex_pattern”}模式。请参阅:MongoDB RegEx语法限制
这不是一个完整的正则表达式教程,但在看到上面一篇投票率很高的模棱两可的帖子后,我受启发运行这些测试。
> ['abbbb','bbabb','bbbba'].forEach(function(v){db.test_collection.insert({val: v})})
> db.test_collection.find({val: /a/})
{ "val" : "abbbb" }
{ "val" : "bbabb" }
{ "val" : "bbbba" }
> db.test_collection.find({val: /.*a.*/})
{ "val" : "abbbb" }
{ "val" : "bbabb" }
{ "val" : "bbbba" }
> db.test_collection.find({val: /.+a.+/})
{ "val" : "bbabb" }
> db.test_collection.find({val: /^a/})
{ "val" : "abbbb" }
> db.test_collection.find({val: /a$/})
{ "val" : "bbbba" }
> db.test_collection.find({val: {'$regex': 'a$'}})
{ "val" : "bbbba" }
可以使用正则表达式进行查询:
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") });
如果使用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') } );
下面是使用正则表达式进行字符串搜索的不同类型的要求和解决方案。
您可以使用包含单词的正则表达式,例如like。也可以使用$options=>i进行不区分大小写的搜索。
包含字符串
db.collection.find({name:{'$regex' : 'string', '$options' : 'i'}})
不包含字符串,仅包含正则表达式
db.collection.find({name:{'$regex' : '^((?!string).)*$', '$options' : 'i'}})
完全不区分大小写的字符串
db.collection.find({name:{'$regex' : '^string$', '$options' : 'i'}})
以字符串开头
db.collection.find({name:{'$regex' : '^string', '$options' : 'i'}})
以字符串结尾
db.collection.find({name:{'$regex' : 'string$', '$options' : 'i'}})
将正则表达式备忘表作为书签,并作为您可能需要的任何其他更改的参考。
我找到了一个免费的工具来将MySQL查询转换为MongoDB:http://www.querymongo.com/
我检查了几个问题。在我看来,几乎所有这些都是正确的。据此,答案是
db.users.find({
"name": "%m%"
});