Search code examples
javamongodblistkotlinbson

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


Solution

  • The converter class can help you on that:

    package simple.sample.mongo.dao;
    
    import com.mongodb.client.model.Filters;
    import com.mongodb.client.model.Sorts;
    import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
    import org.springframework.stereotype.Component;
    import simple.sample.mongo.dao.base.BaseDAO;
    import simple.sample.mongo.models.TodoDocument;
    
    import java.util.List;
    import java.util.stream.Collectors;
    
    @Component
    public class TodoDAO {
    
        private final MappingMongoConverter converter;
        private final BaseDAO dao;
    
        public TodoDAO(MappingMongoConverter converter, BaseDAO dao) {
            this.converter = converter;
            this.dao = dao;
        }
    
        // see for more converters https://github.com/spring-projects/spring-data-examples/tree/main/mongodb/example/src/main/java/example/springdata/mongodb/converters
        public List<TodoDocument> find(String description) {
            return dao.find("todos",
                            Filters.regex("description", description),
                            Sorts.ascending("description"), 100, 0)
                    .stream().map(doc -> converter.read(TodoDocument.class, doc))
                    .collect(Collectors.toList());
        }
    
    }
    

    Where TodoDocument is a mongo collection mapped to java class.

    You can either use TodoRepository to query the document store or get connection from MongoTemplate in order to get access to more flexible queries.

    The more complete sourcecode can be found in this link