Convert DBObject to a POJO using MongoDB Java Driver

Ankur picture Ankur · Oct 7, 2011 · Viewed 57.4k times · Source

MongoDB seems to return BSON/JSON objects.

I thought that surely you'd be able to retrieve values as Strings, ints etc. which can then be saved as POJO.

I have a DBObject (instantiated as a BasicDBObject) as a result of iterating over a list ... (cur.next()).

Is the only way (other than using some sort of persistence framework) to get the data into a POJO to use a JSON serlialiser/deserialiser?

My method looks like this:

public List<User> findByEmail(String email){
         DBCollection userColl;
         try {
            userColl = Dao.getDB().getCollection("users"); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace();}
            DBCursor cur = userColl.find();
            List<User> usersWithMatchEmail = new ArrayList<User>();

            while(cur.hasNext()) {
               // this is where I want to convert cur.next() into a <User> POJO
               usersWithMatchEmail.add(cur.next());
            }
        return null;
    }

EDIT: It's pretty obvious, just do something like this.

Answer

chris mathias picture chris mathias · Jun 13, 2013

Let Spring do the heavy lifting with the stuff it already has built for this...

The real trick is: mongoTemplate.getConverter().read(Foo.class, obj);

For example, when using a DBCursor -

while (cursor.hasNext()) { 
    DBObject obj = cursor.next(); 
    Foo foo = mongoTemplate.getConverter().read(Foo.class, obj);  
    returnList.add(foo); 
}

http://revelfire.com/spring-data-mongodb-convert-from-raw-query-dbobject/