我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
当前回答
In
使用Python的PyMongoMongoose使用Node.jsJongo,使用Javamgo,使用Go
您可以执行以下操作:
db.users.find({'name': {'$regex': 'sometext'}})
其他回答
您已经得到了答案,但要匹配不区分大小写的正则表达式,可以使用以下查询:
db.users.find ({ "name" : /m/i } ).pretty()
/m/i中的i表示不区分大小写,.pretty()提供了更漂亮的输出。
对于MongoDB Compass,您需要使用严格的模式语法,例如:
{ "text": { "$regex": "^Foo.*", "$options": "i" } }
(在MongoDB Compass中,使用“而不是”很重要)
正则表达式的处理成本很高。
另一种方法是创建文本索引,然后使用$search进行搜索。
创建要搜索的字段的文本索引:
db.collection.createIndex({name: 'text', otherField: 'text'});
在文本索引中搜索字符串:
db.collection.find({
'$text'=>{'$search': "The string"}
})
如果您使用的是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);
}
有多种方法可以实现这一点。
最简单的一个:
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中找到。