【发布时间】:2018-11-14 04:17:57
【问题描述】:
我有一个名为 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 中某些元素的slice 作为投影。
即假设我的文档是这样定义的:
@Document(collection = "myCollection")
data class MyDocument(@Id val myId : String, val myArray : List<MyItem>)
MyItem 的定义如下:
data class MyItem(val x: Int, val y: String)
现在我想创建一个函数,该函数返回 MyItem 的列表,给定具有特定 ID 的 MyDocument 的特定偏移量和项目计数(或“页面”)。
这是我尝试过的(使用projections):
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))
是它返回一个包含MyItem(x=3, y="c") 和MyItem(x=4, y="d") 的Flux,但它是空的。
生成的 MongoDB 查询如下所示:
{
"find" : "myCollection",
"filter" : {
"_id" : "1"
},
"projection" : {
"myArray" : 1
},
"skip" : 2,
"limit" : 2,
"batchSize" : 256
}
我怀疑发生的事情是 Pageable 实例在聚合 (MyDocument) 上运行,而不是在 myArray 字段“内部”运行,这就是为什么我怀疑我想以某种方式使用 $slice 运算符而是。
我怎样才能做到这一点?如果使用ReactiveMongoRepository 不起作用,那么我可以使用ReactiveMongoOperations。
【问题讨论】:
标签: spring mongodb spring-boot kotlin spring-data-mongodb