首页 > 解决方案 > 使用 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

标签: springmongodbspring-bootkotlinspring-data-mongodb

解决方案


我设法通过更改来解决这个问题:

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))

推荐阅读