嗨,我是mongodb的新手,我想将JSONObject转换为Document,然后将其存储到mongodb.这是我编码的内容.我在json中获得了一个服务api.
CloseableHttpResponse response = httpClient.execute(get);
HttpEntity entity = response.getEntity();
JSONObject Rat = new JSONObject(EntityUtils.toString(entity));
Run Code Online (Sandbox Code Playgroud)
然后我想将这个鼠保存为mongodb文件,然后将其插入mongodb或mysql,以便我以后可以显示它.我觉得有点像
Document doc = new Document(....);
coll.insertOne(doc); /*where coll is
MongoCollection<Document> coll = db.getCollection("rates"); */
Run Code Online (Sandbox Code Playgroud)
但是如何从JSONObject转换为Document呢?
我是新手JAVA
,MONGODB
并且一直在学习如何尝试理解这些技术是否符合我对产品的要求.
我目前陷入了无法将文档(记录)JAVA
插入我的MONGODB
集合的程度.
我正在使用新的MONGODB
version 3.0
.
代码到目前为止
MongoCollection<Document> coll = db.getCollection("Collection");
String json = "{'class':'Class10', 'student':{'name':'Alpha', 'sex':'Female'}, {'name':'Bravo', 'sex':'Male'}}";
Run Code Online (Sandbox Code Playgroud)
我找到了将其转换为DBObject
类型的代码.
DBObject dbObject = (DBObject)JSON.parse(json);
Run Code Online (Sandbox Code Playgroud)
但我想新版本MONGODB
没有插入方法,而是有insertOne method
.
coll.insertOne()
要求输入采用Document格式,不接受DBObject格式.
coll.insertOne((Document) dbObject);
Run Code Online (Sandbox Code Playgroud)
给出了错误
com.mongodb.BasicDBObject cannot be cast to org.bson.Document
Run Code Online (Sandbox Code Playgroud)
有人可以帮我正确的类型铸造,并给我一个链接,我可以找到并学习相同的?
问候.