Spring Data MongoDB Convert From Raw Query (DBObject)

I had the use case of needing to query mongodb through spring data directly with more or less a raw json query.  The first part was easy:

DBObject dbObject = (DBObject) JSON.parse(query);
DBCursor cursor = mongoTemplate.getCollection(“foo”).find(dbObject);

In spite of the fact that this turned out to be so trivial, I burnt several hours trying to find a solution to mapping the return objects back to my pojo/model/class.  Most solutions I found had me trying to use GSON or Jackson (directly) – basically working AROUND the logic I KNEW must be in there somewhere.

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

I just couldn’t do the hack in good conscience so I kept digging.  The solution turned out to be trivial as well, but either well documented or not easily google searched.

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

SO it goes...