BsonDocument to binary using Java

150 views
Skip to first unread message

Roy Kim

unread,
Oct 10, 2018, 6:19:24 PM10/10/18
to BSON
Hello, group.

I'm trying to encode BsonDocument to binary and transfer with Thrift's binary transformation.
After receiving the binary. decode and use it

I just can't find a way to do it with java.
Hope there is something like below.


BsonDocument bsonDocument = new BsonDocument (~~~);
byte[] binary = bsonDocument.encode();

//send binary with RPC
//receive binary.
BsonDocument  receivedBsonDocument = BsonDocument.decode(binary);


Does anyone know anything similar to this?

Jeff Yemin

unread,
Oct 11, 2018, 12:05:53 AM10/11/18
to BSON
Hi Roy,

You can use the RawBsonDocument class to handle the encoding and decoding for you:

BsonDocument document = new BsonDocument("x", new BsonInt32(1));

RawBsonDocument rawBsonDocument = new RawBsonDocument(document,
new BsonDocumentCodec());

ByteBuffer byteBuffer = rawBsonDocument.getByteBuffer().asNIO();

// Thift ...

// not really safe to call ByteBuffer.array(), but doing it for simplicity here
byte[] bytes = byteBuffer.array();

RawBsonDocument rawBsonDocument2 = new RawBsonDocument(bytes);

BsonDocument decodedDocument = rawBsonDocument2.decode(new BsonDocumentCodec());

Note also that you can avoid the initial decoding of the document by going directly to RawBsonDocument from MongoCollection:

MongoCollection<RawBsonDocument> coll = database.getCollection("test", RawBsonDocument.class);          


Regards,
Jeff 
Reply all
Reply to author
Forward
0 new messages