Java操作mongodb小记

JSONArray jsonArr = JSONArray.fromObject(menuContent);
			JSONObject jsonObj = null;
			Mongo mongo = new Mongo(ResourceUtil.getConfigByName("MongoDB_IP"), Integer.valueOf(ResourceUtil.getConfigByName("MongoDB_Port")));
			DB db = mongo.getDB(ResourceUtil.getConfigByName("MongoDB_Dbname"));
			DBCollection menu = db.getCollection("Menu");
			DBCursor menuCursor = null;
			long count = 0;
			BasicDBList dbList = null;
			boolean insertFlag = false;
			for(int i=0,len=jsonArr.size();i<len;i++){
				jsonObj = (JSONObject)jsonArr.get(i);
				jsonObj.remove("_id");
				String unid = jsonObj.get("unid").toString();
				String name = jsonObj.get("name").toString();
				dbList = new BasicDBList();
				dbList.add(new BasicDBObject("unid",unid));
				dbList.add(new BasicDBObject("name",name));
				count = menu.count(new BasicDBObject("$or",dbList));
				if(count==0){//根据unid或者name找不到记录,则标志为新增记录
					insertFlag = true;
				}
				count = 0;
				if(insertFlag){
					//检查菜单是否存在父菜单
					count = menu.count(new BasicDBObject("unid",jsonObj.get("punid")));
					if(count==0){//当根据punid找不到,则根据pname查找
						DBObject pMenu = menu.findOne(new BasicDBObject("name",jsonObj.get("pname")), new BasicDBObject("unid",1));
						//替换掉要导入的punid
						jsonObj.put("punid", pMenu.get("unid"));
					}
					//删除掉附加的键值
					jsonObj.remove("pname");
					//新增记录
					menu.insert(new BasicDBObject(jsonObj));
				}else{
					//修改菜单记录
					BasicDBObject updateMenu = new BasicDBObject();
					updateMenu.put("deleteFlag", jsonObj.get("deleteFlag"));
					updateMenu.put("disabled", jsonObj.get("disabled"));
					updateMenu.put("imgPath", jsonObj.get("imgPath"));
					updateMenu.put("modifyTime", jsonObj.get("modifyTime"));
					updateMenu.put("sortNum", jsonObj.get("sortNum"));
					updateMenu.put("subCount", jsonObj.get("subCount"));
					updateMenu.put("tip", jsonObj.get("tip"));
					updateMenu.put("type", jsonObj.get("type"));
					updateMenu.put("value", jsonObj.get("value"));
					
					menu.update(new BasicDBObject("$or",dbList), new BasicDBObject("$set",updateMenu));
				}
			}

你可能感兴趣的:(Java操作mongodb小记)