我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
当前回答
您有两个选择:
db.users.find({"name": /string/})
or
db.users.find({"name": {"$regex": "string", "$options": "i"}})
对于第二个,您有更多的选项,如选项中的“i”,以使用不区分大小写的方式查找。
关于“字符串”,可以使用“.string.”(%string%),或“string.*”(string%)和“.*string”(%sstring)。您可以根据需要使用正则表达式。
其他回答
如果使用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') } );
您可以在MongoDB中使用正则表达式。
例如
db.users.find({"name": /^m/})
使用JavaScript RegExp
按空格拆分名称字符串,并生成单词数组映射到迭代循环,并将字符串转换为名称中每个单词的正则表达式
let name=“My name”.split(“”).map(n=>新RegExp(n));console.log(名称);
结果:
[/My/, /Name/]
有两种情况可以匹配字符串,
$in:(类似于$or条件)
尝试在表达式中使用$。要在$in查询表达式中包含正则表达式,只能使用JavaScript正则表达式对象(即/patter/)。例如:
db.users.find({ name: { $in: name } }); // name = [/My/, /Name/]
$all:(类似于$和条件)文档应包含所有单词
db.users.find({ name: { $all: name } }); // name = [/My/, /Name/]
使用嵌套的$and和$or条件和$regex
有两种情况可以匹配字符串,
$或:(类似于$in条件)
db.users.find({
$or: [
{ name: { $regex: "My" } },
{ name: { $regex: "Name" } }
// if you have multiple fields for search then repeat same block
]
})
游戏场
$和:(类似于$all条件)文档应包含所有单词
db.users.find({
$and: [
{
$and: [
{ name: { $regex: "My" } },
{ name: { $regex: "Name" } }
]
}
// if you have multiple fields for search then repeat same block
]
})
游戏场
如果您想在MongoDB中进行“like”搜索,那么应该使用$regex。通过使用它,查询将是:
db.product.find({name:{$regex:/m/i}})
有关更多信息,您也可以阅读文档-$regex
下面是使用正则表达式进行字符串搜索的不同类型的要求和解决方案。
您可以使用包含单词的正则表达式,例如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'}})
将正则表达式备忘表作为书签,并作为您可能需要的任何其他更改的参考。