如何使用 Java/Kotlin 只获取 MongoDB 文档中数组的最后一项

问题描述 投票:0回答:1

如何使用 MongoDB Java 或 Kotlin 驱动程序仅获取 MongoDB 文档中数组的最后一项

无需加载整个文档或可能很长的列表

假设我们有这个数据类:


@Serializable
data class LiveChatRoom(
    @SerialName("_id")
    @Contextual
    val id: ObjectId = ObjectId(),
    val messages: List<ChatMessage> = emptyList(),
)

private val rooms = database.getCollection<LiveChatRoom>("rooms")

此代码确实有效,但它将加载文档和整个列表,这对于非常大的列表来说可能效率低下:


val message = rooms.find(Filters.eq(LiveChatRoom::userId.name, userId)).singleOrNull()?.messages?.lastOrNull()

java mongodb kotlin nosql mongodb-java
1个回答
0
投票

这个解决方案对我有用:


 rooms.find(Filters.eq(LiveChatRoom::userId.name, userId))
                    .projection(
                        Projections.fields(
                            Projections.include(LiveChatRoom::messages.name),
                            Projections.slice(LiveChatRoom::messages.name, -1),
                        )
                    ).singleOrNull()?.messages?.firstOrNull()

我不确定这是否是最好的解决方案

投影数组切片 使用 slice() 方法投影数组切片 一个数组。

以下示例投影了前 6 个元素 温度数组:

data class Results(val temperatures: List<YearlyTemperature.MonthlyTemperature>)
val filter = Filters.empty()
// First half of the year
val projection = Projections.fields(
    Projections.slice(YearlyTemperature::temperatures.name, 6),
    Projections.excludeId()
)
val resultsFlow = collection.find<Results>(filter)
    .projection(projection)
resultsFlow.collect { println(it) }

在官方文档

中阅读更多相关信息
© www.soinside.com 2019 - 2024. All rights reserved.