我想用SQL查询一些东西,比如查询:

SELECT * FROM users  WHERE name LIKE '%m%'

如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。


当前回答

如果您想在MongoDB中进行“like”搜索,那么应该使用$regex。通过使用它,查询将是:

db.product.find({name:{$regex:/m/i}})

有关更多信息,您也可以阅读文档-$regex

其他回答

如果您有字符串变量,则必须将其转换为正则表达式,因此MongoDB将对其使用类似的语句。

const name = req.query.title; //John
db.users.find({ "name": new Regex(name) });

结果与:

db.users.find({"name": /John/})

如果您想在MongoDB中进行“like”搜索,那么应该使用$regex。通过使用它,查询将是:

db.product.find({name:{$regex:/m/i}})

有关更多信息,您也可以阅读文档-$regex

db.users.insert({name: 'patrick'})
db.users.insert({name: 'petra'})
db.users.insert({name: 'pedro'})

因此:

For:

db.users.find({name: /a/})  // Like '%a%'

输出:patrick,petra

For:

db.users.find({name: /^pa/}) // Like 'pa%'

输出:patrick

For:

db.users.find({name: /ro$/}) // Like '%ro'

输出:pedro

前面的答案完美地回答了有关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.*”*/

正则表达式的处理成本很高。

另一种方法是创建文本索引,然后使用$search进行搜索。

创建要搜索的字段的文本索引:

db.collection.createIndex({name: 'text', otherField: 'text'});

在文本索引中搜索字符串:

db.collection.find({
  '$text'=>{'$search': "The string"}
})