Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store byte[] in MongoDB using Java

Tags:

java

mongodb

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
like image 961
sanchapereira Avatar asked Dec 11 '22 22:12

sanchapereira


2 Answers

The problem is not your code but how you check if both arrays - input and output array - are equal. It seems you are just comparing the results of calling toString() on both results. But toString() is not overridden for array types, so it is actually Object.toString() which just returns the type and hash code of an object:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

So [B@719f369d means: 'Array of bytes' ([B) with hash code 0x719f369d. It has nothing to do with the array content.

In your example, input and output arrays are two different objects, hence they have different memory addresses and hash codes (due to the fact, that hashCode() is also not overridden for array types).

Solution

If you want to compare the contents of two byte arrays, call Arrays.equals(byte[], byte[]).

If you want to print the content of a byte array, call Arrays.toString(byte[]) to convert the content into a human readable String.

like image 138
isnot2bad Avatar answered Dec 28 '22 07:12

isnot2bad


MongoDB has support org.bson.types.Binary type

You can use:

BasicDBObject("_id", Binary(session.getIp().getAddress()))

the binary comparisons will work

like image 29
Hett Avatar answered Dec 28 '22 06:12

Hett