Convert DBObject to a POJO using MongoDB Java Driver

Though a late answer , someone might find this useful.

I use GSON to convert from BasicDBObject to my own POJO which is TinyBlogDBObject

TinyBlogDBObject obj = convertJSONToPojo(cursor.next().toString());

private static TinyBlogDBObject convertJSONToPojo(String json){

    Type type = new TypeToken< TinyBlogDBObject >(){}.getType();

    return new Gson().fromJson(json, type);

}

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

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/