java向mongoDB中插入Json

2015/12/25 08:49
阅读数 518
第一种方法,是使用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); 第二种方法是使用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()); 第三种方法是使用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)); 第四种方法,也就是最简单的,即直接插入JSON格式数据 String json ="{'database' : 'mkyongDB','table' : 'hosting',"+ "'detail' : {'records' : 99, 'index' : 'vps_index1', 'active' : 'true'}}}"; DBObject dbObject =(DBObject)JSON.parse(json); collection.insert(dbObject);
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部