0

Is it possible to somehow write a BsonDocument object into file like BSON (not in JSON format)? I am using Java with MongoDB Java Driver for writing BsonDocuments.

I am trying somthing like this:

BsonDocument bson = BsonDocument.parse(someJSONString);
bson.writeBSONtoFile("someFilepath"); //this method

I know that this method will not work, but I am looking for something like this.

Kaan
  • 5,434
  • 3
  • 19
  • 41
nejko
  • 1
  • 3
  • Have you seen: [How could I write a BsonDocument object into a file, and read it again, using Java](https://stackoverflow.com/questions/38689874/how-could-i-write-a-bsondocument-object-into-a-file-and-read-it-again-using-ja) – Abra Dec 27 '19 at 18:47
  • Yes but this is exactly i don't want to do. This is saving bson like json – nejko Dec 27 '19 at 18:50

1 Answers1

0

OK, I have found the workaround. The json string convert to bsonDocument and then with DocumentCodec get byte array which it is written into file.

BsonDocument bson = BsonDocument.parse(someJSONString);

BasicOutputBuffer outputBuffer = new BasicOutputBuffer();
BsonBinaryWriter writer = new BsonBinaryWriter(outputBuffer);
new BsonDocumentCodec().encode(writer, bson, EncoderContext.builder().isEncodingCollectibleDocument(true).build());
byte[] byteArr = outputBuffer.toByteArray();
writeToFile(byteArr);

Many thanks to this guy/post How to directly convert MongoDB Document do Jackson JsonNode in Java

nejko
  • 1
  • 3