Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Java Driver: Convert BsonDocument to Document and back

I am using the MongoDB Java Driver for my project to access my database from Java.

I usually use Document as it's quite easy to use and all methods in MongoDBCollection, such as find() work with it and return Document instances.

However, in some cases I want to use the equivalent BsonDocument which is more verbose but offers type-safety by implementing Map<String,BsonValue>, which Document does not have because it implements Map<String,Object>.

I am able to convert a Document into a BsonDocument with this:

BsonDocument bsonDoc = document.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry());

The problem here is, that all methods in MongoDBCollection, like insertOne() only take Document instances, so I can not use these.


For me, it looks like there are 2 ways to solve this problem:

If the BsonDocument created by toBsonDocument() is in some way backed by the orginal Document, I could use the original Document instance even when I made modifications to the BsonDocument, because the original Document would reflect these changes, right? Does it work this way or is the BsonDocument just a copy?

The second way would be to convert from BsonDocument back to Document. Is this in some way possible?


Thanks in advance!

like image 387
fusionlightcat Avatar asked Mar 13 '18 18:03

fusionlightcat


2 Answers

Assuming you have an instance of CodecRegistry, you can convert BsonDocument to Document and vice-versa using this adapter:

public class DocumentAdapter {
    private final CodecRegistry registry;
    private final Codec<Document> codec;

    public DocumentAdapter(CodecRegistry registry) {
        this.registry = registry;
        this.codec = registry.get(Document.class);
    }

    public Document fromBson(BsonDocument bson) {
        return codec.decode(bson.asBsonReader(), DecoderContext.builder().build());
    }

    public BsonDocument toBson(Document document) {
        return document.toBsonDocument(BsonDocument.class, registry);
    }
}
like image 82
Denis Itskovich Avatar answered Oct 16 '22 01:10

Denis Itskovich


public static Document bsonToDocument(BsonDocument bsonDocument) {
    DocumentCodec codec = new DocumentCodec();
    DecoderContext decoderContext = DecoderContext.builder().build();
    return codec.decode(new BsonDocumentReader(bsonDocument), decoderContext);
}
like image 36
Georgy Gobozov Avatar answered Oct 15 '22 23:10

Georgy Gobozov