Can't find a codec for my class Can't find a codec for my class mongodb mongodb

Can't find a codec for my class


You need to configure a CodecRegistry which will manage the translation from bson to your pojos:

MongoClientURI connectionString = new MongoClientURI("mongodb://localhost:27017");MongoClient mongoClient = new MongoClient(connectionString);CodecRegistry pojoCodecRegistry = org.bson.codecs.configuration.CodecRegistries.fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), org.bson.codecs.configuration.CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build()));MongoDatabase database = mongoClient.getDatabase("testdb").withCodecRegistry(pojoCodecRegistry);  

PS: You could statically import org.bson.codecs.configuration.CodecRegistries.fromRegistries and org.bson.codecs.configuration.CodecRegistries.fromProviders.

A full example could be found in github.
The Mongodb java driver documentation contains also an article about managing pojos (The link is for the 3.8.0 driver version).


Documentation:MongoDB Driver Quick Start - POJOs

After following the above document, if you are still getting error, then

you could be using a generic document inside your collection like

class DocStore {  String docId:  String docType;  Object document; // this will cause the BSON cast to throw a codec error  Map<String, Object> document; // this won't}

And still, you would want to cast your document from POJO to Map

mkyong comes to rescue.

As for the fetch, it works as expected but you might want to cast from Map to your POJO as a post-processing step, we can find some good answers here

Hope it helps! 🙂️


Follow the quick start guide for POJO. You need to register the codec to make the translation of your POJOs (Plain Old Java Object) to/from BSON:http://mongodb.github.io/mongo-java-driver/3.7/driver/getting-started/quick-start-pojo/