sanchapereira sanchapereira - 7 days ago 10
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);
collection.insertOne(doc.getDocument());

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

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

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

Answer

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 - https://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/binary/Base64.html

Comments