Searching for documents with mongoDB

Asked

Viewed 464 times

2

I am using mongoDB 3.2 with Java.

You can save a mongoDB query to a list of objects in a class of mine?

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

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

I actually do 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;
}

Thanks in advance!

  • 2 options. use Reflection for popular object based on attribute name. Use a Orm that already does it for you. I preferably don’t like orms so having to use data mappers.

1 answer

0


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

On mongodb’s own site there are several options to be used.

To not stick to dependencies, it is possible to make a mapper for Reflection manually defining a service that has a method that waits for the type that comes from mongodb and maps to a type of object that you need by tapping the name of the class attribute with that of the mongodb document by Reflection.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.