我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
当前回答
正则表达式的处理成本很高。
另一种方法是创建文本索引,然后使用$search进行搜索。
创建要搜索的字段的文本索引:
db.collection.createIndex({name: 'text', otherField: 'text'});
在文本索引中搜索字符串:
db.collection.find({
'$text'=>{'$search': "The string"}
})
其他回答
在Go和mgo驱动程序中:
Collection.Find(bson.M{"name": bson.RegEx{"m", ""}}).All(&result)
其中结果是所查找类型的结构实例。
Use:
db.customer.find({"customerid": {"$regex": "CU_00000*", "$options": "i"}}).pretty()
当我们搜索字符串模式时,最好使用上面的模式,因为我们不确定大小写。
您有两个选择:
db.users.find({"name": /string/})
or
db.users.find({"name": {"$regex": "string", "$options": "i"}})
对于第二个,您有更多的选项,如选项中的“i”,以使用不区分大小写的方式查找。
关于“字符串”,可以使用“.string.”(%string%),或“string.*”(string%)和“.*string”(%sstring)。您可以根据需要使用正则表达式。
前面的答案完美地回答了有关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)