我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
当前回答
字符串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,帕尔马
其他回答
在PHP中,可以使用以下代码:
$collection->find(array('name'=> array('$regex' => 'm'));
在Go和mgo驱动程序中:
Collection.Find(bson.M{"name": bson.RegEx{"m", ""}}).All(&result)
其中结果是所查找类型的结构实例。
以下是使用“从”范例的命令:
db.customer.find({"customer_name" : { $regex : /^startswith/ }})
您已经得到了答案,但要匹配不区分大小写的正则表达式,可以使用以下查询:
db.users.find ({ "name" : /m/i } ).pretty()
/m/i中的i表示不区分大小写,.pretty()提供了更漂亮的输出。
下面是使用正则表达式进行字符串搜索的不同类型的要求和解决方案。
您可以使用包含单词的正则表达式,例如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'}})
将正则表达式备忘表作为书签,并作为您可能需要的任何其他更改的参考。