-1

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

0

1 Answer 1

0

This solution worked for me:


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

I'm not sure if this the best solution though

Project an Array Slice Use the slice() method to project a slice of an array.

The following example projects the first 6 elements of the temperatures array:

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

Read more about it in the official docs

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.