我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
当前回答
似乎有理由同时使用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" }
其他回答
下面是使用正则表达式进行字符串搜索的不同类型的要求和解决方案。
您可以使用包含单词的正则表达式,例如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'}})
将正则表达式备忘表作为书签,并作为您可能需要的任何其他更改的参考。
有多种方法可以实现这一点。
最简单的一个:
db.users.find({"name": /m/})
{ <field>: { $regex: /pattern/, $options: '<options>' } }
{ <field>: { $regex: 'pattern', $options: '<options>' } }
{ <field>: { $regex: /pattern/<options> } }
db.users.find({ "name": { $regex: "m"} })
更多详细信息可以在$regex中找到。
正则表达式的处理成本很高。
另一种方法是创建文本索引,然后使用$search进行搜索。
创建要搜索的字段的文本索引:
db.collection.createIndex({name: 'text', otherField: 'text'});
在文本索引中搜索字符串:
db.collection.find({
'$text'=>{'$search': "The string"}
})
在SQL中,“like”查询如下所示:
select * from users where name like '%m%'
在MongoDB控制台中,如下所示:
db.users.find({"name": /m/}) // Not JSON formatted
db.users.find({"name": /m/}).pretty() // JSON formatted
此外,pretty()方法将在所有地方生成一个格式化的JSON结构,这样可读性更强。
如果您使用的是PHP,可以使用MongoDB数据对象包装器,如下所示:
$model = new MongoDB_DataObject();
$model->query("select * from users where name like '%m%'");
while($model->fetch()) {
var_dump($model);
}
Or:
$model = new MongoDB_DataObject('users);
$model->whereAdd("name like '%m%'");
$model->find();
while($model->fetch()) {
var_dump($model);
}