ArkadyB ArkadyB - 2 months ago 4x
Java Question

MongoDB casting documents into custom types

Is there some way to read from MongoDB values to objects of my type, without converting them from SimpleDBObject?

I have tried to get all documents from collection with

but when I iterate through them I get

Can't find a codec for interface com.mynamespace.models.interfaces.Profile.

What's the correct way? I use standard Java driver.

As far as i remember in C# and Couchbase i was simply writing/reading documents into my custom types. What's the way here?


Something that I have used in the past is Mongo Jack. This provides a simple wrapper that, according to their documentation, directly maps POJOs from the Mongo stream, without the intermediary SimpleDBObject. This also uses the Jackson library, so you can use Jackson serialization and de-serialization annotations.

This is what the website says:

Deserialises queried objects directly from the MongoDB stream, making it one of the (if not the) fastest object mappers for MongoDB out there.

Perhaps this is what you are looking for, yes?

Here's the example from the website:

JacksonDBCollection<MyObject, String> coll = JacksonDBCollection.wrap(dbCollection, MyObject.class,
MyObject myObject = ...
WriteResult<MyObject, String> result = coll.insert(myObject);
String id = result.getSavedId();
MyObject savedObject = coll.findOneById(id);