How to register a Custom Document Codec ,using the Java Driver


1)If i have those 3 classes


To encode,decode ,all documents to MyDocument ,root ones and embeded

BsonType.DOCUMENT <----> MyDocument.class

How to tell mongoDB Java driver to use my classes?

(For now i dont want to change the functionallity so for now
i just copied the code from Document/DocumentCodec/DocumentCodecProvider
to my classes,and replaced Document with MyDocument)

2)Can i add those classes from the application code,so i dont have to make
customized java driver with my extra classes?

The Main part of my attempt

I made 3 classes (as part of my application)
MyDocument (code from
MyDocumentCoded (code from,replacing Document with MyDocument)
MyDocumentCodecProvider(code from DocumentCodecProvider,replacing Document with MyDocument)

Codec<MyDocument> myDocumentCodec = new MyDocumentCodec();

//I commented the below code,because it seems that wasnt being used.
Map<BsonType, Class<?>> replacements = new HashMap<BsonType, Class<?>>();
replacements.put(BsonType.DOCUMENT, MyDocument.class);
BsonTypeClassMap bsonTypeClassMap = new BsonTypeClassMap(replacements);
MyDocumentCodecProvider myDocumentCodecProvider = new MyDocumentCodecProvider(bsonTypeClassMap);
CodecRegistry defaultRegistry = MongoClientSettings.getDefaultCodecRegistry();

CodecRegistry codecRegistry = CodecRegistries.fromRegistries(

MongoClientSettings settings = MongoClientSettings.builder().codecRegistry(codecRegistry).build();
MongoClient mongoClient = MongoClients.create(settings);

MongoDatabase database = mongoClient.getDatabase("mydb");

MongoCollection<MyDocument> collection = database.getCollection("test",MyDocument.class);

This worked for the root Document,but to make it work for the nested ones i had to change also
the (my MyDocumentCodecProvider wasnt used,even if i un-comment the lines)
I edit the original java driver code,and i destroyed this way the Document,which isnt what
i wanted.

public <T> Codec<T> get(final Class<T> clazz, final CodecRegistry registry)
        if (clazz == CodeWithScope.class) {
            return (Codec<T>) new CodeWithScopeCodec(registry.get(Document.class));

        if (clazz == Document.class)
            //return (Codec<T>) new DocumentCodec(registry, bsonTypeClassMap, valueTransformer);
            return (Codec<T>) new MyDocumentCodec(registry, bsonTypeClassMap, valueTransformer);

        return null;

I am stuck days,thank you in advance.