Java 保存 JSON 到 MongoDB 时数据类型转换问题
这是因为 MongoDB 中的数据类型与 Java 中的数据类型不完全一致,MongoDB 中只有一种数据类型——BSON(Binary JSON),它包含了 Java 中的几乎所有数据类型,但是在 Java 中的数据类型需要转换成对应的 BSON 数据类型才能正确保存在 MongoDB 中。
在保存数据之前,需要先将 Java 中的数据类型转换成对应的 BSON 数据类型,可以使用 MongoDB 提供的 BSON 工具类进行转换,例如:
import org.bson.Document;
import org.bson.types.ObjectId;
Document document = new Document();
document.append('number', 123);
document.append('string', 'hello');
document.append('timestamp', new Date());
ObjectId objectId = new ObjectId();
document.append('_id', objectId);
collection.insertOne(document);
在上述代码中,通过 Document 对象将 Java 中的数据转换成了对应的 BSON 数据类型,并使用 insertOne() 方法将数据保存到 MongoDB 中。
需要注意的是,在保存数据时需要将 Java 中的时间戳转换成 MongoDB 中的日期类型,可以使用 new Date() 方法将时间戳转换成日期类型,然后在保存到 MongoDB 中。
原文地址: https://www.cveoy.top/t/topic/oxiP 著作权归作者所有。请勿转载和采集!