You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过KMongo在服务端基于courseTitle匹配过滤课程?

KMongo实现courseTitle模糊匹配查询

针对字符串类型的courseTitle字段,你之前使用的contains是KMongo专为数组类型设计的操作符,因此无法生效。以下是几种正确的实现方式:

1. 精确匹配

如果需要完全匹配某个课程名称,使用eq操作符:

val courses = database.getCollection<Course>()
val exactMatchCourses = courses.find(Course::courseTitle eq "目标课程名称").toList()

2. 大小写敏感的部分匹配

要查询包含指定子串的课程,使用regex操作符:

// 匹配包含"query"子串的课程(大小写敏感)
val partialMatchCourses = courses.find(Course::courseTitle regex "query").toList()

// 或者用正则表达式对象,支持更复杂的匹配规则
val partialMatchCourses = courses.find(Course::courseTitle regex Regex("query")).toList()

3. 大小写不敏感的部分匹配

如果需要忽略大小写匹配,可通过正则选项实现:

// 方式一:使用RegexOption.IGNORE_CASE
val caseInsensitiveCourses = courses.find(
    Course::courseTitle regex Regex("query", RegexOption.IGNORE_CASE)
).toList()

// 方式二:使用MongoDB的options参数
val caseInsensitiveCourses = courses.find(
    Course::courseTitle regex "query" withOptions "i"
).toList()

4. 在Aggregate的Match阶段使用

如果需要在聚合管道的match阶段应用该过滤条件,写法如下:

val filtercourse = courses.aggregate(
    match(Course::courseTitle regex "query")
).toList()

内容的提问来源于stack exchange,提问作者Keval Kanpariya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 22:35:53