我们希望用不同的方式,通过JAVA代码向Mongodb插入以上格式的JSON数据
第一种方法,是使用BasicDBObject,方法如下代码所示:
BasicDBObject document = new BasicDBObject();
document.put("database", "mkyongDB");
document.put("table", "hosting");
BasicDBObject documentDetail = new BasicDBObject();
documentDetail.put("records", "99");
documentDetail.put("index", "vps_index1");
documentDetail.put("active", "true");
document.put("detail", documentDetail);
collection.insert(document);
document.put("database", "mkyongDB");
document.put("table", "hosting");
BasicDBObject documentDetail = new BasicDBObject();
documentDetail.put("records", "99");
documentDetail.put("index", "vps_index1");
documentDetail.put("active", "true");
document.put("detail", documentDetail);
collection.insert(document);
第二种方法是使用BasicDBObjectBuilder对象,如下代码所示:
BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
.add("database", "mkyongDB")
.add("table", "hosting");
BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start()
.add("records", "99")
.add("index", "vps_index1")
.add("active", "true");
documentBuilder.add("detail", documentBuilderDetail.get());
collection.insert(documentBuilder.get());
.add("database", "mkyongDB")
.add("table", "hosting");
BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start()
.add("records", "99")
.add("index", "vps_index1")
.add("active", "true");
documentBuilder.add("detail", documentBuilderDetail.get());
collection.insert(documentBuilder.get());
第三种方法是使用Map对象,代码如下:
Map documentMap =new HashMap();
documentMap.put("database", "mkyongDB");
documentMap.put("table", "hosting");
Map documentMapDetail =new HashMap();
documentMapDetail.put("records", "99");
documentMapDetail.put("index", "vps_index1");
documentMapDetail.put("active", "true");
documentMap.put("detail", documentMapDetail);
collection.insert(new BasicDBObject(documentMap));
documentMap.put("database", "mkyongDB");
documentMap.put("table", "hosting");
Map documentMapDetail =new HashMap();
documentMapDetail.put("records", "99");
documentMapDetail.put("index", "vps_index1");
documentMapDetail.put("active", "true");
documentMap.put("detail", documentMapDetail);
collection.insert(new BasicDBObject(documentMap));
第四种方法,也就是最简单的,即直接插入JSON格式数据
String json ="{'database' : 'mkyongDB','table' : 'hosting',"+
"'detail' : {'records' : 99, 'index' : 'vps_index1', 'active' : 'true'}}}";
DBObject dbObject =(DBObject)JSON.parse(json);
collection.insert(dbObject);
"'detail' : {'records' : 99, 'index' : 'vps_index1', 'active' : 'true'}}}";
DBObject dbObject =(DBObject)JSON.parse(json);
collection.insert(dbObject);
这里使用了JSON的parse方法,将解析后的JSON字符串转变为DBObject对象后再直接插入到collection中去。