简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM