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
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
.
MongoDB has support org.bson.types.Binary
type
You can use:
BasicDBObject("_id", Binary(session.getIp().getAddress()))
the binary comparisons will work
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With