2023-05-23

MongoDB Document - how to convert into model class?

I have the following java code that I am using to paginated a response from mongodb, that works as expected:

List<Document> documents = collection.find()
        .skip(offset)
        .limit(limit)
        .into(new ArrayList<>());

Instead of a generic org.bson.Document what I want to return is a list of my specific model kotlin class Person.

@JsonInclude(JsonInclude.Include.NON_NULL)
class Person {

    @JsonProperty("id")
    var id: Long? = null

    @JsonProperty("name")
    var name: String? = null
    
}

When I try the following:

    List<Person> documents = collection.find()
            .skip(offset)
            .limit(limit)
            .into(new ArrayList<Person>());

I get compile error:

Inferred type 'A' for type parameter 'A' is not within its bound; should implement 'java.util.Collection<? super org.bson.Document>'

How can I resolve this?

The library used here is: org.mongodb:bson:3.12.1



No comments:

Post a Comment