2

I have Java webapp with connection to MongoDB and utilizing custom codecs to encode/decode domain specific Java POJOs to/from MongoDB documents. Connection URL is provided to application via environment variable. The URL can contain options but per URL format documentation https://docs.mongodb.com/manual/reference/connection-string/ it is not possible to specify codecs in URL. So my natural choice would be to use MongoClientOptions builder to combine options from URI and new CodecRegistry with my codecs:

MongoClientOptions optsWithCodecs = MongoClientOptions.builder(
    mongoURI.getOptions()).codecRegistry(myCodecRegistry).build();

The problem is that MongoClient does not provide constructor that would accept URI and MongoClientOptions, there's constructor that takes just URI:

public MongoClient(final MongoClientURI uri) {
    super(uri);
}

That makes me parse URI manually duplicating some code from MongoClient private methods and then use one of other constructors accepting options. I would like to find a better way to configure MongoClient with custom codecs. I'm using Mongo Java driver version 3.3.0

2 Answers 2

2
Builder optionsBuilder = MongoClientOptions.builder().codecRegistry(myCodecRegistry);
MongoClient mongo = new MongoClient(new MongoClientURI(connectionString, optionsBuilder));
Sign up to request clarification or add additional context in comments.

Comments

1

You can try something like this.

 MongoClientOptions optsWithCodecs = MongoClientOptions.builder(
 mongoURI.getOptions()).codecRegistry(myCodecRegistry).build();
 MongoClientURI mongoClientUri = new MongoClientURI(uri, optsWithCodecs);
 MongoClient mongoClient = new MongoClient(mongoClientUri);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.