1 year ago

#385747

test-img

Sebastian Wollner

How to convert a POJO to an BSON using MongoDB Java Driver

I've searched for a way to to convert a POJO into a BSON document. Unfortunately, the only answer you can find on the web is that MongoDB does this implicitly through the db.getCollection("some collection", Pojo.class) function. But there are some use cases where you want to convert a POJO into a BSON document.

One could be that you want to update a nested document in your MongoDB root document. However, this isn't possible with the provided methods of the MongoDB Java Driver. The only way to do this is to write all the values manually in to a update expression.

db.getCollection("some collection", Pojo.class)
  .updateOne(Filter.eq(id), Updates.set("myNestedDoc", new Document("some", "value"));

But it would be nice to do the same with a POJO. The advantages are obvious! Less duplicated code, better maintainable and less error prune.

But how can we accomplish this? As described above, no answer can be found on the web. So I've searched the MongoDB Java Driver source code and found a way! The BsonDocumentWrapper is a utility class to wrap a object as a BsonDocument. It uses the CodecRegistry which does the conversion internally.

db.getCollection("some collection", Pojo.class)
  .updateOne(Filter.eq(id), 
             Updates.set("myNestedDoc",
                         BsonDocumentWrapper.asBsonDocument(lom, codecRegistry)));
)

You could also use the CodecRegistry object directly.

Pojo myPojo...
BsonDocument unwrapped = new BsonDocument();
BsonWriter writer = new BsonDocumentWriter(unwrapped);
Encoder<Pojo> encoder = codecRegistry.get(Pojo.class);
encoder.encode(writer, myPojo, EncoderContext.builder().build());
this.unwrapped = unwrapped;

But the utility class is more readable and maintainable.

This way you can safely use your existing POJOs to update your nested structures. Keep in mind that you will replace the whole sub object, not only the fields that have been changed!

If you for some reason need to convert a BSON into a POJO you can use this sniped:

BsonDocument bson...
BsonReader reader = new BsonDocumentReader(bson);
Decoder<Pojo> encoder = codecRegistry.get(Pojo.class);        
Pojo myPojo = encoder.decode(reader, DecoderContext.builder().build());

I hope this is useful to someone ;)

java

mongodb

pojo

bson

0 Answers

Your Answer

Accepted video resources