sanchapereira sanchapereira - 1 year ago 146
Java Question

Store byte[] in MongoDB using Java

I insert a document into a collection with a field of byte[]. When I query the inserted document to get that field, it returns a different byte[]. How do I fix that?

byte[] inputBytes = ...

MongoCollection<Document> collection = _db.getCollection("collectionx");
Document doc = new Document("test", 1).append("val", inputBytes);

MongoCursor<Document> result = collection.find(eq("test", 1)).iterator();
Document retrived_doc =;

byte[] outputBytes = ((Binary)retrived_doc.get("val")).getData();

// inputBytes = [B@719f369d
// outputBytes = [B@7b70cec2

Answer Source

You can encode byte array and store it in doc also decode it after extraction to retrieve original.

static String   encodeBase64String(byte[] binaryData)

Encodes binary data using the base64 algorithm but does not chunk the output.

static byte[]   decodeBase64(String base64String)

Decodes a Base64 String into octets.

Please refer this link -

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download