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

Spring Data MongoDB中Kotlin的List嵌套对象KProperty查询问题

Kotlin Spring Data MongoDB 类型安全查询集合嵌套属性

场景背景

我们在Kotlin环境中使用Spring Data MongoDB时,借助org.springframework.data.mongodb.core.query.TypedCriteriaExtensions提供的类型安全扩展,可便捷构建查询Criteria。现有数据类定义如下:

data class Foo(
  val id: String, 
  val oneBar: Bar, 
  val bars: List<Bar>)

data class Bar(val thingy: String)

已知单个嵌套对象的类型安全查询写法:

// 查询id匹配的文档
criterion = criterion + (Foo::id isEqualTo "id")
// 查询oneBar.thingy匹配的文档
criterion = criterion + (Foo::oneBar / Bar::thingy isEqualTo "thingy")

集合嵌套属性的查询方案

针对Foo中List<Bar>类型的bars属性,无需额外的"list相关操作",直接通过属性路径拼接即可实现类型安全查询,写法如下:

// 查询bars数组中存在任意元素的thingy等于"thingy"的文档
criterion = criterion + (Foo::bars / Bar::thingy isEqualTo "thingy")

原理说明

这种写法利用TypedCriteriaExtensions的路径拼接能力,自动将Foo::bars / Bar::thingy转换为MongoDB的查询路径bars.thingy。MongoDB原生支持此类数组查询:只要数组中存在至少一个元素匹配thingy = "thingy"的条件,整个Foo文档就会被命中。

复杂数组查询示例

如果需要查询数组中存在同时满足多个条件的元素(对应MongoDB的$elemMatch),可以使用all操作符结合多条件组合:

// 假设Bar新增anotherProp字段
data class Bar(val thingy: String, val anotherProp: Int)

// 查询bars数组中存在元素同时满足thingy="thingy"且anotherProp=123的文档
criterion = criterion + (Foo::bars all (Bar::thingy isEqualTo "thingy" and Bar::anotherProp isEqualTo 123))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 09:14:59