Missing Codecs in MongoDB

What to do when you get org.bson.codecs.configuration.CodecConfigurationException: cant find a codec for class java.math.BigDecimal..

Mike Hostetler

When upgrading a project’s Mongo driver from 2.13.0 to 3.4.2, we got the following exception:

org.bson.codecs.configuration.CodecConfigurationException: can't find a codec for class java.math.BigDecimal.

Well it seems that Mongo doesn’t support BigDecimal any longer. There we made our own BigdDecimal Codec. If you search for the ”can't find a codec for class” error, you inevitably end up at this StackOverflow entry. However that is about saving nested, custom objects into Mongo. If you search for a while longer you will end up in the Mongo docs that has a simple example with Integer. Seems easy to adopt that for BigDecimal.

But when we did that, we got the same error. it seemed like Mongo was just ignoring our call to the CodecRegistry! The problem was what is described here – we were using a BasicDBObject and not a Document so the Mongo driver wasn’t hitting the CodecRegistry.

I made a Gist overview of how we got it working. The key was adding the Transformer via the static class with this line:  BSON.addEncodingHook(BigDecimal.class, new BigDecimalTransformer()); . We needed both that Transformer and the Codec in the registry for it to work.

I hope that this post can save someone else a few hours/days of head-scratching.

Share this Post

Related Blog Posts

JVM

Spring Webflux - Functional Endpoints

November 16th, 2017

This post will look at how to set up a simple router and get global error handling in place using the new webflux.fn routing available in Spring 5.

Iain Coffield
JVM

Handy Gradle Recipes

November 8th, 2017

Some tweaks and hints for gradle

Mike Hostetler
JVM

Functional Testing With Embedded Kafka

October 25th, 2017

Functional Testing With Embedded Kafka in a Spring Boot Application using a Gradle task.

Brendon Anderson

About the author

Mike Hostetler

Sr. Consultant

Mike has almost 20 years of experience in technology. He started in networking and Unix administration, and grew into technical support and QA testing. But he has always done some development on the side and decided a few years ago to pursue it full-time. His history of working with users gives Mike a unique perspective on writing software.