user2325154 user2325154 - 2 months ago 20
Java Question

How to return an ArrayList of objects in MongoDB and Java?

I have a method in my DAO which looks like this

ProductDao.java

public List<Document> getAllProducts() {
return mongoCollection.find().into(new ArrayList<Document>());
}


What I would like instead is

//return a list of Product instead of Document
public List<Product> getAllProducts() {
return mongoCollection.find().into(new ArrayList<Product>());
}


pom.xml

<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.3.0</version>
</dependency>


How can I achieve this?

Answer

There is a few java libs that can help you with it:

Morhpia - http://code.google.com/p/morphia/

Spring Data for MongoDB - http://www.springsource.org/spring-data/mongodb

Also, you can do something like:

public List<Product> getAllProducts() {
    DBCursor cur = mongoCollection.find();
    List<Product> products = new ArrayList<Product>();
    while(cur.hasNext()) {
        products.add(cur.next());
    }
    return products;
}