我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
当前回答
您可以在MongoDB中使用正则表达式。
例如
db.users.find({"name": /^m/})
其他回答
类似的查询如下所示:
db.movies.find({title: /.*Twelve Monkeys.*/}).sort({regularizedCorRelation : 1}).limit(10);
对于Scala ReactiveMongo API,
val query = BSONDocument("title" -> BSONRegex(".*" + name + ".*", "")) // like
val sortQ = BSONDocument("regularizedCorRelation" -> BSONInteger(1))
val cursor = collection.find(query).sort(sortQ).options(QueryOpts().batchSize(10)).cursor[BSONDocument]
前面的答案完美地回答了有关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.*”*/
使用如下匹配的正则表达式。“i”显示不区分大小写。
var collections = mongoDatabase.GetCollection("Abcd");
var queryA = Query.And(
Query.Matches("strName", new BsonRegularExpression("ABCD", "i")),
Query.Matches("strVal", new BsonRegularExpression("4121", "i")));
var queryB = Query.Or(
Query.Matches("strName", new BsonRegularExpression("ABCD","i")),
Query.Matches("strVal", new BsonRegularExpression("33156", "i")));
var getA = collections.Find(queryA);
var getB = collections.Find(queryB);
似乎有理由同时使用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" }
在PHP中,可以使用以下代码:
$collection->find(array('name'=> array('$regex' => 'm'));