How to only get the last item of an array in MongoDB Document using MongoDB Java or Kotlin driver
Without loading the whole document or the list which can be very long
Let's say we have this data class:
@Serializable
data class LiveChatRoom(
@SerialName("_id")
@Contextual
val id: ObjectId = ObjectId(),
val messages: List<ChatMessage> = emptyList(),
)
private val rooms = database.getCollection<LiveChatRoom>("rooms")
This code does work but it will load the the document and the whole list which can be inefficient for a very huge list:
val message = rooms.find(Filters.eq(LiveChatRoom::userId.name, userId)).singleOrNull()?.messages?.lastOrNull()