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!
getCollection
I can use to get other types of documents in the collection instance. I will look into this and see if I can get it to work! – Insane