spring - 使用 Spring Data MongoDB ReactiveMongoRepository 进行切片投影?
问题描述
我有一个名为的集合myCollection
,其中包含具有以下格式的文档:
{
"_id" : "1",
"myArray" : [ { x: 1, y: "a" }, { x: 2, y: "b" }, { x: 3, y: "c" }, { x: 4, y: "d" }, { x: 5, y: "e" }]
}
我想做的是构造一个查询,该查询将某些元素的切片myArray
作为投影返回。
即假设我的文档是这样定义的:
@Document(collection = "myCollection")
data class MyDocument(@Id val myId : String, val myArray : List<MyItem>)
whereMyItem
定义如下:
data class MyItem(val x: Int, val y: String)
现在我想创建一个函数,该函数返回具有特定 id的MyItem
给定偏移量和项目计数(或“页面”)的列表。MyDocument
这是我尝试过的(使用预测):
data class MyArrayProjection(val myArray: List<MyItem>)
interface MyRepository : ReactiveMongoRepository<MyDocument, String> {
fun findByMyId(myId: String, pageable: Pageable): Flux<MyArrayProjection>
}
使用例如调用此函数时我想看到什么
myRepository.findByMyId("1", PageRequest.of(1, 2))
是它返回一个Flux
包含MyItem(x=3, y="c")
,MyItem(x=4, y="d")
但它是空的。
生成的 MongoDB 查询如下所示:
{
"find" : "myCollection",
"filter" : {
"_id" : "1"
},
"projection" : {
"myArray" : 1
},
"skip" : 2,
"limit" : 2,
"batchSize" : 256
}
我怀疑正在发生的是Pageable
实例在聚合 ( MyDocument
) 上运行,而不是在字段“内部”,myArray
这就是为什么我怀疑我想以某种方式使用$slice运算符。
我怎样才能做到这一点?如果使用ReactiveMongoRepository不起作用,那么我可以使用ReactiveMongoOperations。
解决方案
我设法通过更改来解决这个问题:
interface MyRepository : ReactiveMongoRepository<MyDocument, String> {
fun findByMyId(myId: String, pageable: Pageable): Flux<MyArrayProjection>
}
到:
interface MyRepository : ReactiveMongoRepository<MyDocument, String> {
@Query(value = "{ '_id' : ?0 }", fields = "{ 'myArray': { '\$slice': ?1 } }")
fun findByMyId(myId: String, slice: Array<Int>): Flux<MyArrayProjection>
}
然后使用以下命令调用它:
myRepository.findByMyId("1", arrayOf(1, 2))
推荐阅读
- mysql - Laradock 无法访问 root@localhost
- python-3.x - 打开后如何阻止.py文件关闭?使用python 3.9?
- sql - 使用 SQL 进行多关键字搜索
- javascript - Angular Karma - 组件未定义
- ios - Xcode 调试器在文件上启用
- python - 当秒数为 0 时,每 15 分钟运行一次 python 程序
- css - 带有宽表和水平滚动条的 Bootstrap4
- postgresql - 在插入原始表时聚合数据
- r - 根据R中的离散标签集标记散点(带滑块)
- elasticsearch - 弹性搜索迁移 503 - cluster_block_exception