[英]Parse JSON into a MONGODB docment
I am new to JAVA
and MONGODB
and have been learning both to try and understand if these technologies would meet my requirements for a product. 我是
JAVA
和MONGODB
并且一直在学习如何尝试和理解这些技术是否符合我对产品的要求。
I am currently stuck in a point where I am not able to insert documents(records) from JAVA
into my MONGODB
collection. 我目前陷入困境,我无法将
JAVA
文档(记录)插入到我的MONGODB
集合中。
I am using the new MONGODB
version 3.0
. 我正在使用新的
MONGODB
version 3.0
。
Code so far 代码到目前为止
MongoCollection<Document> coll = db.getCollection("Collection");
String json = "{'class':'Class10', 'student':{'name':'Alpha', 'sex':'Female'}, {'name':'Bravo', 'sex':'Male'}}";
I have found code to convert this to a DBObject
type. 我找到了将其转换为
DBObject
类型的代码。
DBObject dbObject = (DBObject)JSON.parse(json);
But I guess the new version of MONGODB
does not have the insert method but instead has the insertOne method
. 但我想
MONGODB
的新版本没有insert方法,而是有insertOne method
。
coll.insertOne()
requires that the input be in the Document format and does not accept the DBObject format. coll.insertOne()
要求输入采用Document格式,不接受DBObject格式。
coll.insertOne((Document) dbObject);
gives the error 给出了错误
com.mongodb.BasicDBObject cannot be cast to org.bson.Document
Can someone help me with the right type casting and give me a link where I could find and learn the same? 有人可以帮我正确的类型铸造,并给我一个链接,我可以找到并学习相同的?
Regards. 问候。
使用在Document类中定义的静态解析(String json)方法。
The problem is that you are using an older version(BasicDBObject) that is not compatible with version 3.0. 问题是您使用的是与版本3.0不兼容的旧版本(BasicDBObject)。
But there is a way for 2.0 users to use BasicDBObject.An overload of the getCollection method allows clients to specify a different class for representing BSON documents. 但是2.0用户有一种方法可以使用BasicDBObject.An的getCollection方法重载允许客户端指定一个不同的类来表示BSON文档。
The following code must work for you. 以下代码必须适合您。
MongoCollection<BasicDBObject> coll = db.getCollection("Collection", BasicDBObject.class);
coll.insertOne(dbObject);
I used google gson for convert pojo to json, and this is work perfect. 我使用谷歌gson转换pojo到json,这是完美的工作。
private final MongoCollection<Document> collection;
//my save
String json = gson.toJson(data);//data is User DTO, just pojo!
BasicDBObject document = (BasicDBObject) JSON.parse(json);
collection.insertOne(new Document(document));
Java mongodb driver version is 3.4.2 Java mongodb驱动程序版本是3.4.2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.