java - 使用 Java 将 byte[] 存储在 MongoDB 中

标签 java mongodb

我将一个文档插入到一个字段为 byte[] 的集合中。当我查询插入的文档以获取该字段时,它返回一个不同的 byte[]。我该如何解决?

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

最佳答案

问题不在于您的代码,而在于您如何检查两个数组(输入和输出数组)是否相等。您似乎只是在比较对两个结果调用 toString() 的结果。但是 toString() 没有被数组类型覆盖,所以它实际上是 Object.toString()它只返回对象的类型和哈希码:

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())

因此 [B@719f369d 表示:“字节数组”([B),哈希码为 0x719f369d。与数组内容无关。

在您的示例中,输入和输出数组是两个不同的对象,因此它们具有不同的内存地址和哈希码(事实上,hashCode() 也不会被数组类型覆盖) .

解决方案

如果要比较两个字节数组的内容,调用Arrays.equals(byte[], byte[]) .

如果要打印字节数组的内容,调用Arrays.toString(byte[])将内容转换为人类可读的 String

关于java - 使用 Java 将 byte[] 存储在 MongoDB 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30566905/

相关文章:

c# - 在 .net core 中建模 mongodb 存储的引用关系

Java - 如何使用 while 循环解决此计算

java - 使用特定顺序对 (Array)List 进行排序

java - 如何避免 Java 反射中的魔术字符串

java - JDBC 和 pgbouncer 可以与 createStatement 一起使用吗

node.js - Mongoose - 仅按日期部分排序日期,忽略时间

java - 如何从sql表中扣除一个值?

node.js - 无法使用 insertMany 使用 compose for mongodb 插入记录

mongodb - 使用MongoDB Go驱动程序,如何设置连接池?

javascript - 如何在 node.js 和 MongoDb 的 javascript 中混契约(Contract)步和异步代码