mongodb java 不等于_java对mongodb数据库进行数据操作

1 packagemongodb;2

3 importjava.io.ByteArrayOutputStream;4 importjava.io.IOException;5 importjava.io.ObjectOutputStream;6 importjava.lang.reflect.Field;7 importjava.util.ArrayList;8 importjava.util.HashMap;9 importjava.util.Iterator;10 importjava.util.List;11 importjava.util.Map;12 importjava.util.Map.Entry;13 importjava.util.regex.Pattern;14

15 importorg.apache.commons.beanutils.ConvertUtilsBean;16

17 importcom.mongodb.AggregationOptions;18 importcom.mongodb.AggregationOutput;19 importcom.mongodb.BasicDBList;20 importcom.mongodb.BasicDBObject;21 importcom.mongodb.Cursor;22 importcom.mongodb.DB;23 importcom.mongodb.DBCollection;24 importcom.mongodb.DBCursor;25 importcom.mongodb.DBObject;26 importcom.mongodb.Mongo;27 importcom.mongodb.MongoClient;28 importcom.mongodb.WriteResult;29 importcom.mongodb.gridfs.GridFS;30 importcom.mongodb.util.JSON;31

32 importnet.sf.json.JSONObject;33

34 public classMongoDBClient {35

36 private static final String mongoHost = "127.0.1";37 private static final int mongoPort = 27017;38 private static final String dbName = "runoob";39 private static final String root = "root";40 private static final String password = "123456";41

42 private static Map clsMap = new HashMap();43 private static MongoClient client = null;44 private staticMongo mongo;45 private staticDB mongodb;46 private static GridFS fs = null;47

48 //获取数据库

49 public staticDB getMongodb(){50 if(mongodb != null){51 returnmongodb;52 }else{53 mongo = newMongo(mongoHost,mongoPort);54 mongodb =mongo.getDB(dbName);55 System.out.println("连接成功");56 fs = newGridFS(mongodb);57 }58 returnmongodb;59 }60

61

62 private staticDBCursor getCursor(DB con, String tablename, String field, Object value){63 DBCollection col =con.getCollection(tablename);64 BasicDBObject basic = newBasicDBObject();65 if(!field.equals("") && value !=null){66 basic.put(field, value);//创建需要查询的文本

67 }68 DBCursor cursor = col.find(basic);//通过find方法返回结果集

69 returncursor;70 }71

72 private static DBCursor getCursor(DB con, String tablename, Mapmap){73 DBCollection col =con.getCollection(tablename);74 BasicDBObject basic = newBasicDBObject();75 if(!map.isEmpty() && map!=null){76 for(Entryentry:map.entrySet()){77 String key =entry.getKey();78 Object object =entry.getValue();79 basic.put(key, object);80 }81 }82 DBCursor cursor =col.find(basic);83 returncursor;84 }85

86 //插入数据

87 public static WriteResult insert(String tablename, Mapmap){88 DBCollection col =getMongodb().getCollection(tablename);89 BasicDBObject basic = newBasicDBObject();90 if(map!=null && !map.isEmpty()){91 String field;92 Object object;93 for(Entryentry:map.entrySet()){94 field =entry.getKey();95 object =entry.getValue();96 basic.put(field, object);97 }98 }99 //使用BasicDBObject对象向集合中添加数据

100 WriteResult result =col.insert(basic);101 returnresult;102 }103

104 //删除数据

105 public static void delete(String tablename, Mapmap){106 DBCollection col =getMongodb().getCollection(tablename);107 BasicDBObject basic = newBasicDBObject();108 if(map!=null && !map.isEmpty()){109 String field;110 Object value;111 for(Entryentry:map.entrySet()){112 field =entry.getKey();113 value =entry.getValue();114 basic.put(field, value);115 }116 }117 col.remove(basic);118 }119

120 //更新数据

121 public static WriteResult update(String tablename, Map

122 mapSel, MapmapValue){123 DBCollection col =getMongodb().getCollection(tablename);124 BasicDBObject basic = newBasicDBObject();125 BasicDBObject setobject = newBasicDBObject();126 BasicDBObject valueobject = newBasicDBObject();127 WriteResult result = null;128 String field;129 Object value;130 if(!mapSel.isEmpty() && mapSel!=null && !mapValue.isEmpty() &&

131 mapValue!=null){132 for(Entryentry:mapSel.entrySet()){133 field =entry.getKey();134 value =entry.getValue();135 basic.put(field, value);//保存所更新时,查询的条件

136 }137 for(Entryentry:mapValue.entrySet()){138 field =entry.getKey();139 value =entry.getValue();140 valueobject.put(field, value);//保存更新的字段值

141 }142 setobject.append("$set", valueobject);143 result =col.update(basic, setobject);144 }145 returnresult;146 }147

148 //获取Map类型数据1

149 public static MapgetMapData(String tablename, String field, Object value){150 Map map = new HashMap();151 DBCursor cursor = null;152 cursor =getCursor(getMongodb(),tablename,field,value);153 while(cursor.hasNext()){154 map = (Map) cursor.next();155 }156 cursor.close();157 mongo.close();158 returnmap;159 }160 //获取Map类型数据2

161 public static Map getMapData(String tablename, Mapmap){162 Map map1 = new HashMap();163 DBCursor cursor = null;164 cursor =getCursor(getMongodb(),tablename,map);165 while(cursor.hasNext()){166 map = (Map) cursor.next();167 }168 cursor.close();169 mongo.close();170 returnmap;171 }172 //获取List类型数据1

173 public static List>getListData(String tablename, String field, Object value){174 List> list = new ArrayList>();175 Map map = new HashMap();176 DBCursor cursor = null;177 cursor =getCursor(getMongodb(),tablename,field,value);178 while(cursor.hasNext()){179 map = (Map) cursor.next();180 list.add(map);181 }182 cursor.close();183 mongo.close();184 returnlist;185 }186 //获取List类型数据2

187 public static List> getListData(String tablename, Mapmap){188 List> list = new ArrayList>();189 Map map1 = new HashMap();190 DBCursor cursor = null;191 cursor =getCursor(getMongodb(),tablename,map);192 while(cursor.hasNext()){193 map1 = (Map) cursor.next();194 list.add(map1);195 }196 cursor.close();197 mongo.close();198 returnlist;199 }200

201

202 /*添加数据的四中操作*/

203 //添加JSON数据

204 public static voidinsertJsonBean(String tablename,Object object){205 DBCollection col =getMongodb().getCollection(tablename);206 BasicDBObject basic = newBasicDBObject();207 basic =(BasicDBObject) JSON.parse(JSONObject.fromObject(object).toString());208 col.insert(basic);209 }210 //添加JAVA对象

211 public static voidinsertBean(String tablename,Object object)212 throwsIOException{213 DBCollection col =getMongodb().getCollection(tablename);214 BasicDBObject basic = newBasicDBObject();215 //捕获内存缓冲区的数据,转换成字节数组

216 ByteArrayOutputStream outstream = newByteArrayOutputStream();217 ObjectOutputStream out = newObjectOutputStream(outstream);218 out.writeObject(object);219 basic.put("java", outstream.toByteArray());220 col.insert(basic);221 out.close();222 outstream.close();223 }224 //添加LIST-JAVA对象

225 public static void insertListBean(String tablename,Listlist){226 DBCollection col =getMongodb().getCollection(tablename);227 BasicDBObject basic = newBasicDBObject();228 List listdb = new ArrayList();229 for(int i=0;i

236

237 /*查询数据的几种形式*/

238 //查询所有数据

239 public List findAllBean(String tablename,Class clazz) throwsException{240 Object object =clazz.newInstance();241 DBCollection col =getMongodb().getCollection(tablename);242 DBCursor cursor = null;243 Map map = new HashMap();244 Field[] field =clsMap.get(clazz.getName());245 Object value = null;246 Object val = null;247 ConvertUtilsBean cub = newConvertUtilsBean();248 List list = new ArrayList();249 if(field == null){250 field =clazz.getDeclaredFields();251 clsMap.put(clazz.getName(), field);252 }253 cursor =col.find();254 while(cursor.hasNext()){255 map = (Map) cursor.next();256 for(int j=0;j

270 public Object findBean(String tablename,Class clazz,Mapmap)271 throwsException{272 DBCollection col =getMongodb().getCollection(tablename);273 BasicDBObject basic = newBasicDBObject();274 DBCursor cursor = null;275 Map mapfield = new HashMap();276 Object object =clazz.newInstance();277 ConvertUtilsBean cub = newConvertUtilsBean();278 for(Entryentry:map.entrySet()){279 String name =entry.getKey();280 Object value =entry.getValue();281 basic.put(name, value);282 }283 cursor =col.find(basic);284 Field[] field =clsMap.get(clazz.getName());285 if(field == null){286 field =clazz.getDeclaredFields();287 clsMap.put(clazz.getName(), field);288 }289 if(cursor.hasNext()){290 mapfield = (Map) cursor.next();291 }292 for(int i=0;i

305 public ListfindBeanNE(String tablename,Class clazz,String field,Object param)306 throwsException{307 DBCollection col =getMongodb().getCollection(tablename);308 BasicDBObject basicappend = newBasicDBObject();309 Object object =clazz.newInstance();310 DBCursor cursor = null;311 ConvertUtilsBean cub = newConvertUtilsBean();312 Map map = new HashMap();313 List list = new ArrayList();314 Field[] fieldlist =clsMap.get(clazz.getName());315 basicappend.append("$ne", param);316 BasicDBObject basic = newBasicDBObject();317 basic.put(field, param);318 cursor =col.find(basic);319 if(fieldlist == null){320 fieldlist =clazz.getDeclaredFields();321 clsMap.put(clazz.getName(), fieldlist);322 }323 if(cursor == null){324 return null;325 }326 while(cursor.hasNext()){327 map = (Map) cursor.next();328 for(int i=0;i

342 public ListfindBeanByAnd1(String tablename,Class clazz,String field,Object little,Object big)343 throwsException{344 DBCollection col =getMongodb().getCollection(tablename);345 BasicDBObject basic = newBasicDBObject();346 BasicDBObject basicappend = newBasicDBObject();347 Object object =clazz.newInstance();348 DBCursor cursor = null;349 List list = new ArrayList();350 Map map = new HashMap();351 ConvertUtilsBean cub = newConvertUtilsBean();352 Field[] fieldlist =clsMap.get(clazz.getName());353 basicappend.append("$lt", big);354 basicappend.append("$gt", little);355 basic.put(field, basicappend);356 if(fieldlist == null){357 fieldlist =clazz.getDeclaredFields();358 clsMap.put(clazz.getName(), fieldlist);359 }360 cursor =col.find(basic);361 if(cursor == null){362 return null;363 }364 while(cursor.hasNext()){365 map = (Map) cursor.next();366 for(int i=0;i

380 public List findBeanByAnd2(String tablename,Class clazz,Map>map)381 throwsException{382 DBCollection col =getMongodb().getCollection(tablename);383 BasicDBObject basic = newBasicDBObject();384 Object object =clazz.newInstance();385 DBCursor cursor = null;386 List list = new ArrayList();387 Map map1 = new HashMap();388 ConvertUtilsBean cub = newConvertUtilsBean();389 Field[] fieldlist =clsMap.get(clazz.getName());390 for(Entry>entry:map.entrySet()){391 String mapname =entry.getKey();392 Map map2 =entry.getValue();393 BasicDBObject basicappend = newBasicDBObject();394 for(Entryentry1:map2.entrySet()){395 String map2name =entry1.getKey();396 Object map2value =entry1.getValue();397 basicappend.append(map2name, map2value);398 }399 basic.put(mapname, basicappend);400 }401 if(fieldlist == null){402 fieldlist =clazz.getDeclaredFields();403 clsMap.put(clazz.getName(), fieldlist);404 }405 cursor =col.find(basic);406 if(cursor == null){407 return null;408 }409 while(cursor.hasNext()){410 map1 = (Map) cursor.next();411 for(int i=0;i

425 public ListfindBeanByOr1(String tablename,Class clazz,String field,Object param1,Object param2)426 throwsException{427 BasicDBList values = newBasicDBList();428 values.add(new BasicDBObject(field,new BasicDBObject("$gt", param1)));429 values.add(new BasicDBObject(field,new BasicDBObject("$lt", param2)));430 BasicDBObject basic = newBasicDBObject();431 basic.put("$or", values);432 DBCollection col =getMongodb().getCollection(tablename);433 Object object =clazz.newInstance();434 DBCursor cursor = null;435 List list = new ArrayList();436 Map map = new HashMap();437 ConvertUtilsBean cub = newConvertUtilsBean();438 Field[] fieldlist =clsMap.get(clazz.getName());439 if(fieldlist == null){440 fieldlist =clazz.getDeclaredFields();441 clsMap.put(clazz.getName(), fieldlist);442 }443 cursor =col.find(basic);444 if(cursor == null){445 return null;446 }447 while(cursor.hasNext()){448 map = (Map) cursor.next();449 for(int i=0;i

463 public List findBeanByOr2(String tablename,Class clazz,Map>map)464 throwsException{465 DBCollection col =getMongodb().getCollection(tablename);466 BasicDBObject basicobject = newBasicDBObject();467 Object object =clazz.newInstance();468 DBCursor cursor = null;469 List list = new ArrayList();470 Map map1 = new HashMap();471 ConvertUtilsBean cub = newConvertUtilsBean();472 Field[] fieldlist =clsMap.get(clazz.getName());473 Object[] objectlist = null;474 int i =0;475 for(Entry>entry:map.entrySet()){476 String mapname =entry.getKey();477 BasicDBObject basic = newBasicDBObject();478 Map map2 =entry.getValue();479 BasicDBObject basicappend = newBasicDBObject();480 for(Entryentry1:map2.entrySet()){481 String map2name =entry1.getKey();482 Object map2value =entry1.getValue();483 basicappend.append(map2name, map2value);484 }485 basic.put(mapname, basicappend);486 objectlist[i] =basic;487 i++;488 }489 if(fieldlist == null){490 fieldlist =clazz.getDeclaredFields();491 clsMap.put(clazz.getName(), fieldlist);492 }493 basicobject.put("$or", basicobject);494 cursor =col.find(basicobject);495 if(cursor == null){496 return null;497 }498 while(cursor.hasNext()){499 map1 = (Map) cursor.next();500 for(int j=0;j

514 public ListfindBeanByIn(String tablename,Class clazz,String field,Object...objects)515 throwsException{516 DBCollection col =getMongodb().getCollection(tablename);517 BasicDBObject basic = newBasicDBObject();518 DBCursor cursor = null;519 Map mapfield = new HashMap();520 Object object =clazz.newInstance();521 ConvertUtilsBean cub = newConvertUtilsBean();522 BasicDBObject basicappend = newBasicDBObject();523 basicappend.append("$in", objects);524 basic.put(field, basicappend);525 cursor =col.find(basic);526 List list = new ArrayList();527 Field[] fieldlist =clsMap.get(clazz.getName());528 if(fieldlist == null){529 fieldlist =clazz.getDeclaredFields();530 clsMap.put(clazz.getName(), fieldlist);531 }532 while(cursor.hasNext()){533 mapfield = (Map) cursor.next();534 for(int i=0;i

549 public List findBeanBySort(String tablename,Class clazz,String param,intnum)550 throwsException{551 if(num!=1 || num!=-1){552 return null;553 }554 Object object =clazz.newInstance();555 DBCollection col =getMongodb().getCollection(tablename);556 DBCursor cursor = null;557 Map map = new HashMap();558 Field[] field =clsMap.get(clazz.getName());559 Object value = null;560 Object val = null;561 BasicDBObject basic = newBasicDBObject();562 ConvertUtilsBean cub = newConvertUtilsBean();563 List list = new ArrayList();564 basic.append(param, num);565 if(field == null){566 field =clazz.getDeclaredFields();567 clsMap.put(clazz.getName(), field);568 }569 cursor =col.find().sort(basic);570 while(cursor.hasNext()){571 map = (Map) cursor.next();572 for(int j=0;j

586 public List findBeanByPage(String tablename,Class clazz,int size,intpage)587 throwsException{588 if(size<=0){589 return null;590 }591 Object object =clazz.newInstance();592 DBCollection col =getMongodb().getCollection(tablename);593 DBCursor cursor = null;594 Map map = new HashMap();595 Field[] field =clsMap.get(clazz.getName());596 Object value = null;597 Object val = null;598 BasicDBObject basic = newBasicDBObject();599 ConvertUtilsBean cub = newConvertUtilsBean();600 List list = new ArrayList();601 if(field == null){602 field =clazz.getDeclaredFields();603 clsMap.put(clazz.getName(), field);604 }605 cursor = col.find().skip((page-1)*size).sort(newBasicDBObject()).limit(size);606 while(cursor.hasNext()){607 map = (Map) cursor.next();608 for(int j=0;j

622 public ListfindBeanByLike(String tablename,Class clazz,String fieldname,Object param)623 throwsException{624 Object object =clazz.newInstance();625 DBCollection col =getMongodb().getCollection(tablename);626 DBCursor cursor = null;627 Map map = new HashMap();628 Field[] field =clsMap.get(clazz.getName());629 BasicDBObject basic = newBasicDBObject();630 ConvertUtilsBean cub = newConvertUtilsBean();631 List list = new ArrayList();632 //左匹配633 //Pattern parent1 = Pattern.compile("^"+param+".*$",Pattern.CASE_INSENSITIVE);634 //右匹配635 //Pattern pattern2 = Pattern.compile("^.*"+param+"$", Pattern.CASE_INSENSITIVE);636 //全模糊匹配

637 Pattern pattern3 = Pattern.compile("^.*"+param+".*$",Pattern.CASE_INSENSITIVE);638 basic.put(fieldname, pattern3);639 cursor =col.find(basic);640 if(cursor == null){641 return null;642 }643 if(field == null){644 field =clazz.getDeclaredFields();645 clsMap.put(clazz.getName(), field);646 }647 while(cursor.hasNext()){648 map = (Map) cursor.next();649 for(int i=0;i

663 public List findBeanColumn(String tablename,Class clazz,String[] fields,Map>map)664 throwsException{665 DBCollection col =getMongodb().getCollection(tablename);666 BasicDBObject basic = newBasicDBObject();667 Object object =clazz.newInstance();668 DBCursor cursor = null;669 List list = new ArrayList();670 Map map1 = new HashMap();671 ConvertUtilsBean cub = newConvertUtilsBean();672 Field[] fieldlist =clsMap.get(clazz.getName());673 BasicDBObject projection = newBasicDBObject();674 for(int k=0;k>entry:map.entrySet()){678 String mapname =entry.getKey();679 Map map2 =entry.getValue();680 BasicDBObject basicappend = newBasicDBObject();681 for(Entryentry1:map2.entrySet()){682 String map2name =entry1.getKey();683 Object map2value =entry1.getValue();684 basicappend.append(map2name, map2value);685 }686 basic.put(mapname, basicappend);687 }688 if(fieldlist == null){689 fieldlist =clazz.getDeclaredFields();690 clsMap.put(clazz.getName(), fieldlist);691 }692 cursor =col.find(basic, projection);693 if(cursor == null){694 return null;695 }696 while(cursor.hasNext()){697 map1 = (Map) cursor.next();698 for(int i=0;i

712

713 /*聚合操作*/

714 //count

715 public int objectcount(String tablenae, Mapmap){716 DBCollection col =getMongodb().getCollection(tablenae);717 BasicDBObject basic = newBasicDBObject();718 for(Entryentry:map.entrySet()){719 String name =entry.getKey();720 Object value =entry.getValue();721 basic.put(name, value);722 }723 int count =col.find(basic).count();724 returncount;725 }726 //Max与Min

727 public MapmaxObject(String tablenae, String field){728 DBCollection col =getMongodb().getCollection(tablenae);729 BasicDBObject basic = newBasicDBObject();730 basic.put(field, true);731 DBCursor cursor = null;732 Map map = new HashMap();733 cursor =col.find().max(basic);734 while(cursor.hasNext()){735 map = (Map) cursor.next();736 }737 returnmap;738 }739 //Sum

740 public List>sumObject(String tablename,String field,String field1){741 DBCollection col =getMongodb().getCollection(tablename);742 List list = new ArrayList();743 BasicDBObject group = newBasicDBObject();744 BasicDBObject sexdb = newBasicDBObject();745 BasicDBObject agesum = newBasicDBObject();746 Map map = new HashMap();747 List> listmap = new ArrayList>();748 agesum.append("$sum", "$"+field1);749 sexdb.append(field, "$"+field);750 sexdb.append("total", agesum);751 group.append("$group", sexdb);752 list.add(group);753 DBCursor cursor = (DBCursor) col.aggregate(list, AggregationOptions.builder().allowDiskUse(true).build());754 while(cursor.hasNext()){755 map = (Map) cursor.next();756 listmap.add(map);757 }758 returnlistmap;759 }760 //Avg

761 public List>avgObject(String tablename,String field,String field1){762 DBCollection col =getMongodb().getCollection(tablename);763 DBCursor cursor = null;764 BasicDBObject avgobject = newBasicDBObject();765 BasicDBObject object = newBasicDBObject();766 BasicDBObject basic = newBasicDBObject();767 avgobject.append("$avg", "$"+field);768 object.append("avg", avgobject);769 object.append(field1, "$"+field1);770 List list = new ArrayList();771 Map map = new HashMap();772 List> listmap = new ArrayList>();773 list.add(object);774 cursor = (DBCursor) col.aggregate(list, AggregationOptions.builder().allowDiskUse(true).build());775 while(cursor.hasNext()){776 map = (Map) cursor.next();777 listmap.add(map);778 }779 returnlistmap;780 }781

782 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值