Searching for documents with mongoDB

2

I'm using mongoDB 3.2 with Java.

Is it possible to save a mongoDB query in a list of objects of a class of mine?

I want to save the query directly to a list of people.

class Pessoa{
    String nome;
    Date dataNascimento;
    String email;
}

I'm currently doing this, because it's the only way I know:

public List<Pessoa> listar() throws Exception {
    List<Pessoa> listPessoa = new ArrayList<>();

    MongoClient mongoClient = new MongoClient("localhost", 27017);
    MongoDatabase db = mongoClient.getDatabase("dbExemploMongo");
    FindIterable<Document> iterable = db.getCollection("colecao1").find();

    for (Document document : iterable) {

        listPessoa.add(new Pessoa(
                document.getString("nome"),
                document.getDate("datanasc"),
                document.getString("email"))
        );
    }


    return listPessoa;
}

Thank you in advance!

    
asked by anonymous 10.03.2016 / 18:57

1 answer

0

If you are using Spring, you can use the MongoDB module from Spring Data , or if you want just a POJO mapper you can use morphia .

On the mongodb site itself there are several options to use.

In order not to stick to dependencies, you can do a mapper by reflection manually by defining a service that has a method that expects the type that comes from mongodb and maps for a type of object you need by hitting the class attribute name with that of the mongodb document by reflection.

    
10.03.2016 / 23:27