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!
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);
}
}
public static Document bsonToDocument(BsonDocument bsonDocument) {
DocumentCodec codec = new DocumentCodec();
DecoderContext decoderContext = DecoderContext.builder().build();
return codec.decode(new BsonDocumentReader(bsonDocument), decoderContext);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With