我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
当前回答
前面的答案完美地回答了有关MongoDB核心查询的问题。但当使用基于模式的搜索查询时,例如:
{“keywords”:{“$regex”:“^toron.*”}}
or
{“关键字”:{“$regex”:“^toron”}}
在带有@query注释的Spring Boot JPA存储库查询中,使用如下查询:
@Query(value = "{ keyword : { $regex : ?0 } }")
List<SomeResponse> findByKeywordContainingRegex(String keyword);
呼叫应为:
List<SomeResponse> someResponseList = someRepository.findByKeywordsContainingRegex("^toron");
List<SomeResponse> someResponseList = someRepository.findByKeywordsContainingRegex("^toron.*");
但千万不要使用:
List<SomeResponse> someResponseList = someRepository.findByKeywordsContainingRegex("/^toron/");
List<SomeResponse> someResponseList =someRepository.findByKeywordsContainingRegex("/^toron.*/");
需要注意的一点是:每次?@Query语句中的0字段替换为双引号字符串。因此,在这些情况下不应使用正斜杠(/)!在搜索模式中始终使用双引号!!例如,在/^toron/或/^toron上使用“^toron”或“^toron.*”*/
其他回答
对于Go驱动程序:
filter := bson.M{
"field_name": primitive.Regex{
Pattern: keyword,
Options: "",
},
}
cursor, err := GetCollection().Find(ctx, filter)
在$in查询中使用正则表达式(MongoDB文档:$in):
filter := bson.M{
"field_name": bson.M{
"$in": []primitive.Regex{
{
Pattern: keyword,
Options: "",
},
}
}
}
cursor, err := GetCollection().Find(ctx, filter)
在MongoDb中,可以使用likeusingMongoDB引用运算符正则表达式(regex)。
对于相同的Ex。
MySQL - SELECT * FROM users WHERE name LIKE '%m%'
MongoDb
1) db.users.find({ "name": { "$regex": "m", "$options": "i" } })
2) db.users.find({ "name": { $regex: new RegExp("m", 'i') } })
3) db.users.find({ "name": { $regex:/m/i } })
4) db.users.find({ "name": /mail/ })
5) db.users.find({ "name": /.*m.*/ })
MySQL - SELECT * FROM users WHERE name LIKE 'm%'
MongoDb Any of Above with /^String/
6) db.users.find({ "name": /^m/ })
MySQL - SELECT * FROM users WHERE name LIKE '%m'
MongoDb Any of Above with /String$/
7) db.users.find({ "name": /m$/ })
可以使用正则表达式进行查询:
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") });
为了以防万一,有人正在寻找一种SQL LIKE类型的查询,以查找包含字符串数组而不是字符串的键,这里是:
db.users.find({"name": {$in: [/.*m.*/]}})
对于MongoDB Compass,您需要使用严格的模式语法,例如:
{ "text": { "$regex": "^Foo.*", "$options": "i" } }
(在MongoDB Compass中,使用“而不是”很重要)