首页 > 代码库 > java对mongodb数据库进行数据操作

java对mongodb数据库进行数据操作

  1 package mongodb;
  2 
  3 import java.io.ByteArrayOutputStream;
  4 import java.io.IOException;
  5 import java.io.ObjectOutputStream;
  6 import java.lang.reflect.Field;
  7 import java.util.ArrayList;
  8 import java.util.HashMap;
  9 import java.util.Iterator;
 10 import java.util.List;
 11 import java.util.Map;
 12 import java.util.Map.Entry;
 13 import java.util.regex.Pattern;
 14 
 15 import org.apache.commons.beanutils.ConvertUtilsBean;
 16 
 17 import com.mongodb.AggregationOptions;
 18 import com.mongodb.AggregationOutput;
 19 import com.mongodb.BasicDBList;
 20 import com.mongodb.BasicDBObject;
 21 import com.mongodb.Cursor;
 22 import com.mongodb.DB;
 23 import com.mongodb.DBCollection;
 24 import com.mongodb.DBCursor;
 25 import com.mongodb.DBObject;
 26 import com.mongodb.Mongo;
 27 import com.mongodb.MongoClient;
 28 import com.mongodb.WriteResult;
 29 import com.mongodb.gridfs.GridFS;
 30 import com.mongodb.util.JSON;
 31 
 32 import net.sf.json.JSONObject;
 33 
 34 public class MongoDBClient {
 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<String, Field[]> clsMap = new HashMap<String, Field[]>();
 43     private static MongoClient client = null;
 44     private static Mongo mongo;
 45     private static DB mongodb;
 46     private static GridFS fs = null;
 47     
 48     //获取数据库
 49     public static DB getMongodb(){
 50         if(mongodb != null){
 51             return mongodb;
 52         }else{
 53             mongo = new Mongo(mongoHost,mongoPort);
 54             mongodb = mongo.getDB(dbName);
 55             System.out.println("连接成功");
 56             fs = new GridFS(mongodb);
 57             }
 58         return mongodb;
 59         }
 60     
 61     
 62     private static DBCursor getCursor(DB con, String tablename, String field, Object value){
 63         DBCollection col = con.getCollection(tablename);
 64         BasicDBObject basic = new BasicDBObject();
 65         if(!field.equals("") && value !=null){
 66             basic.put(field, value);//创建需要查询的文本
 67         }
 68         DBCursor cursor = col.find(basic);//通过find方法返回结果集
 69         return cursor;
 70     }
 71     
 72     private static DBCursor getCursor(DB con, String tablename, Map<String,Object> map){
 73         DBCollection col = con.getCollection(tablename);
 74         BasicDBObject basic = new BasicDBObject();
 75         if(!map.isEmpty() && map!=null){
 76             for(Entry<String,Object> entry: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         return cursor;
 84     }
 85     
 86     //插入数据
 87     public static WriteResult insert(String tablename, Map<String,Object> map){
 88         DBCollection col = getMongodb().getCollection(tablename);
 89         BasicDBObject basic = new BasicDBObject();
 90         if(map!=null && !map.isEmpty()){
 91             String field;
 92             Object object;
 93             for(Entry<String,Object> entry: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         return result;
102     }
103     
104     //删除数据
105     public static void delete(String tablename, Map<String,Object> map){
106         DBCollection col = getMongodb().getCollection(tablename);
107         BasicDBObject basic = new BasicDBObject();
108         if(map!=null && !map.isEmpty()){
109             String field;
110             Object value;
111             for(Entry<String,Object> entry:map.entrySet()){
112                 field = entry.getKey();
113                 value =http://www.mamicode.com/ entry.getValue();
114                 basic.put(field, value);
115             }
116         }
117         col.remove(basic);
118     }
119     
120     //更新数据
121     public static WriteResult update(String tablename, Map<String,Object> 
122     mapSel, Map<String,Object> mapValue){
123         DBCollection col = getMongodb().getCollection(tablename);
124         BasicDBObject basic = new BasicDBObject();
125         BasicDBObject setobject = new BasicDBObject();
126         BasicDBObject valueobject = new BasicDBObject();
127         WriteResult result = null;
128         String field;
129         Object value;
130         if(!mapSel.isEmpty() && mapSel!=null && !mapValue.isEmpty() &&
131                 mapValue!=null){
132             for(Entry<String,Object> entry:mapSel.entrySet()){
133                 field = entry.getKey();
134                 value =http://www.mamicode.com/ entry.getValue();
135                 basic.put(field, value);//保存所更新时,查询的条件
136             }
137             for(Entry<String,Object> entry:mapValue.entrySet()){
138                 field = entry.getKey();
139                 value =http://www.mamicode.com/ entry.getValue();
140                 valueobject.put(field, value);//保存更新的字段值
141             }
142             setobject.append("$set", valueobject);
143             result = col.update(basic, setobject);
144         }
145         return result;
146     }
147     
148     //获取Map类型数据1
149     public static Map<String,Object> getMapData(String tablename, String field, Object value){
150         Map<String,Object> map = new HashMap<String,Object>();
151         DBCursor cursor = null;
152         cursor = getCursor(getMongodb(),tablename,field,value);
153         while(cursor.hasNext()){
154             map = (Map<String, Object>) cursor.next();
155         }
156         cursor.close();
157         mongo.close();
158         return map;
159     }
160     //获取Map类型数据2
161     public static Map<String,Object> getMapData(String tablename, Map<String,Object> map){
162         Map<String,Object> map1 = new HashMap<String,Object>();
163         DBCursor cursor = null;
164         cursor = getCursor(getMongodb(),tablename,map);
165         while(cursor.hasNext()){
166             map = (Map<String, Object>) cursor.next();
167         }
168         cursor.close();
169         mongo.close();
170         return map;
171     }
172     //获取List类型数据1
173     public static List<Map<String,Object>> getListData(String tablename, String field, Object value){
174         List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
175         Map<String,Object> map = new HashMap<String,Object>();
176         DBCursor cursor = null;
177         cursor = getCursor(getMongodb(),tablename,field,value);
178         while(cursor.hasNext()){
179             map = (Map<String, Object>) cursor.next();
180             list.add(map);
181         }
182         cursor.close();
183         mongo.close();
184         return list;
185     }
186     //获取List类型数据2
187     public static List<Map<String,Object>> getListData(String tablename, Map<String,Object> map){
188         List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
189         Map<String,Object> map1 = new HashMap<String,Object>();
190         DBCursor cursor = null;
191         cursor = getCursor(getMongodb(),tablename,map);
192         while(cursor.hasNext()){
193             map1 = (Map<String, Object>) cursor.next();
194             list.add(map1);
195         }
196         cursor.close();
197         mongo.close();
198         return list;
199     }
200     
201     
202     /*添加数据的四中操作*/
203     //添加JSON数据
204     public static void insertJsonBean(String tablename,Object object){
205         DBCollection col = getMongodb().getCollection(tablename);
206         BasicDBObject basic = new BasicDBObject();
207         basic = (BasicDBObject) JSON.parse(JSONObject.fromObject(object).toString());
208         col.insert(basic);
209     }
210     //添加JAVA对象
211     public static void insertBean(String tablename,Object object) 
212             throws IOException{
213         DBCollection col = getMongodb().getCollection(tablename);
214         BasicDBObject basic = new BasicDBObject();
215         //捕获内存缓冲区的数据,转换成字节数组
216         ByteArrayOutputStream outstream = new ByteArrayOutputStream();
217         ObjectOutputStream out = new ObjectOutputStream(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,List<Object> list){
226         DBCollection col = getMongodb().getCollection(tablename);
227         BasicDBObject basic = new BasicDBObject();
228         List<DBObject> listdb = new ArrayList<DBObject>();
229         for(int i=0;i<list.size();i++){
230             basic = (BasicDBObject) JSON.parse(JSONObject.fromObject(list.get(i)).toString());
231             list.add(basic);
232         }
233         col.insert(listdb);
234     }
235     
236     
237     /*查询数据的几种形式*/
238     //查询所有数据
239     public List<Object> findAllBean(String tablename,Class clazz) throws Exception{
240         Object object = clazz.newInstance();
241         DBCollection col = getMongodb().getCollection(tablename);
242         DBCursor cursor = null;
243         Map<String,Object> map = new HashMap<String,Object>();
244         Field[] field = clsMap.get(clazz.getName());
245         Object value = http://www.mamicode.com/null;
246         Object val = null;
247         ConvertUtilsBean cub = new ConvertUtilsBean();
248         List<Object> list = new ArrayList<Object>();
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<String, Object>) cursor.next();
256             for(int j=0;j<field.length;j++){
257                 String name = field[j].getName();
258                 Field fi = field[j];
259                 if(map.containsKey(name)){
260                     value =http://www.mamicode.com/ map.get(name);
261                     val = cub.convert(value, fi.getType());
262                     fi.set(object, val);
263                 }
264             }
265             list.add(object);
266         }
267         return list;
268     }
269     //查询java对象
270     public Object findBean(String tablename,Class clazz,Map<String,Object> map) 
271             throws Exception{
272         DBCollection col = getMongodb().getCollection(tablename);
273         BasicDBObject basic = new BasicDBObject();
274         DBCursor cursor = null;
275         Map<String,Object> mapfield = new HashMap<String,Object>();
276         Object object = clazz.newInstance();
277         ConvertUtilsBean cub = new ConvertUtilsBean(); 
278         for(Entry<String,Object> entry:map.entrySet()){
279             String name = entry.getKey();
280             Object value =http://www.mamicode.com/ 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<String, Object>) cursor.next();
291         }
292         for(int i=0;i<field.length;i++){
293             Field fi = field[i];
294             String fieldname = fi.getName();
295             if(!mapfield.containsKey(fieldname)){
296                 continue;
297             }
298             Object fieldvalue =http://www.mamicode.com/ mapfield.get(fieldname);
299             Object val = cub.convert(fieldvalue, fi.getType());
300             fi.set(object, val);
301         }
302         return object;
303     }
304     //非等于查询
305     public List<Object> findBeanNE(String tablename,Class clazz,String field,Object param)
306             throws Exception{
307         DBCollection col = getMongodb().getCollection(tablename);
308         BasicDBObject basicappend = new BasicDBObject();
309         Object object = clazz.newInstance();
310         DBCursor cursor = null;
311         ConvertUtilsBean cub = new ConvertUtilsBean();
312         Map<String,Object> map = new HashMap<String,Object>();
313         List<Object> list = new ArrayList<Object>();
314         Field[] fieldlist = clsMap.get(clazz.getName());
315         basicappend.append("$ne", param);
316         BasicDBObject basic = new BasicDBObject();
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<String, Object>) cursor.next();
328             for(int i=0;i<fieldlist.length;i++){
329                 String fieldname = fieldlist[i].getName();
330                 if(!map.containsKey(fieldname)){
331                     continue;
332                 }
333                 Object fieldvalue =http://www.mamicode.com/ map.get(fieldname);
334                 Object val = cub.convert(fieldvalue, fieldlist[i].getType());
335                 fieldlist[i].set(object, val);
336             }
337             list.add(object);
338         }
339         return list;
340     }
341     //单字段and查询
342     public List<Object> findBeanByAnd1(String tablename,Class clazz,String field,Object little,Object big) 
343             throws Exception{
344         DBCollection col = getMongodb().getCollection(tablename);
345         BasicDBObject basic = new BasicDBObject();
346         BasicDBObject basicappend = new BasicDBObject();
347         Object object = clazz.newInstance();
348         DBCursor cursor = null;
349         List<Object> list = new ArrayList<Object>();
350         Map<String,Object> map = new HashMap<String,Object>();
351         ConvertUtilsBean cub = new ConvertUtilsBean();
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<String, Object>) cursor.next();
366             for(int i=0;i<fieldlist.length;i++){
367                 String fieldname = fieldlist[i].getName();
368                 if(!map.containsKey(fieldname)){
369                     continue;
370                 }
371                 Object fieldvalue =http://www.mamicode.com/ map.get(fieldname);
372                 Object val = cub.convert(fieldvalue, fieldlist[i].getType());
373                 fieldlist[i].set(object, val);
374             }
375             list.add(object);
376         }
377         return list;
378     }
379     //多字段and查询
380     public List<Object> findBeanByAnd2(String tablename,Class clazz,Map<String,Map<String,Object>> map) 
381             throws Exception{
382         DBCollection col = getMongodb().getCollection(tablename);
383         BasicDBObject basic = new BasicDBObject();
384         Object object = clazz.newInstance();
385         DBCursor cursor = null;
386         List<Object> list = new ArrayList<Object>();
387         Map<String,Object> map1 = new HashMap<String,Object>();
388         ConvertUtilsBean cub = new ConvertUtilsBean();
389         Field[] fieldlist = clsMap.get(clazz.getName());
390         for(Entry<String,Map<String,Object>> entry:map.entrySet()){
391             String mapname = entry.getKey();
392             Map<String,Object> map2 = entry.getValue();
393             BasicDBObject basicappend = new BasicDBObject();
394             for(Entry<String,Object> entry1:map2.entrySet()){
395                 String map2name = entry1.getKey();
396                 Object map2value =http://www.mamicode.com/ 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<String, Object>) cursor.next();
411             for(int i=0;i<fieldlist.length;i++){
412                 String fieldname = fieldlist[i].getName();
413                 if(!map1.containsKey(fieldname)){
414                     continue;
415                 }
416                 Object fieldvalue =http://www.mamicode.com/ map1.get(fieldname);
417                 Object val = cub.convert(fieldvalue, fieldlist[i].getType());
418                 fieldlist[i].set(object, val);
419             }
420             list.add(object);
421         }
422         return list;
423     }
424     //单字段or查询
425     public List<Object> findBeanByOr1(String tablename,Class clazz,String field,Object param1,Object param2)
426             throws Exception{
427         BasicDBList values = new BasicDBList();
428         values.add(new BasicDBObject(field,new BasicDBObject("$gt", param1)));
429         values.add(new BasicDBObject(field,new BasicDBObject("$lt", param2)));
430         BasicDBObject basic = new BasicDBObject();
431         basic.put("$or", values);
432         DBCollection col = getMongodb().getCollection(tablename);
433         Object object = clazz.newInstance();
434         DBCursor cursor = null;
435         List<Object> list = new ArrayList<Object>();
436         Map<String,Object> map = new HashMap<String,Object>();
437         ConvertUtilsBean cub = new ConvertUtilsBean();
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<String, Object>) cursor.next();
449             for(int i=0;i<fieldlist.length;i++){
450                 String fieldname = fieldlist[i].getName();
451                 if(!map.containsKey(fieldname)){
452                     continue;
453                 }
454                 Object fieldvalue =http://www.mamicode.com/ map.get(fieldname);
455                 Object val = cub.convert(fieldvalue, fieldlist[i].getType());
456                 fieldlist[i].set(object, val);
457             }
458             list.add(object);
459         }
460         return list;
461     }
462     //多字段or查询
463     public List<Object> findBeanByOr2(String tablename,Class clazz,Map<String,Map<String,Object>> map)
464             throws Exception{
465         DBCollection col = getMongodb().getCollection(tablename);
466         BasicDBObject basicobject = new BasicDBObject();
467         Object object = clazz.newInstance();
468         DBCursor cursor = null;
469         List<Object> list = new ArrayList<Object>();
470         Map<String,Object> map1 = new HashMap<String,Object>();
471         ConvertUtilsBean cub = new ConvertUtilsBean();
472         Field[] fieldlist = clsMap.get(clazz.getName());
473         Object[] objectlist = null;
474         int i =0;
475         for(Entry<String,Map<String,Object>> entry:map.entrySet()){
476             String mapname = entry.getKey();
477             BasicDBObject basic = new BasicDBObject();
478             Map<String,Object> map2 = entry.getValue();
479             BasicDBObject basicappend = new BasicDBObject();
480             for(Entry<String,Object> entry1:map2.entrySet()){
481                 String map2name = entry1.getKey();
482                 Object map2value =http://www.mamicode.com/ 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<String, Object>) cursor.next();
500             for(int j=0;j<fieldlist.length;j++){
501                 String fieldname = fieldlist[j].getName();
502                 if(!map1.containsKey(fieldname)){
503                     continue;
504                 }
505                 Object fieldvalue =http://www.mamicode.com/ map1.get(fieldname);
506                 Object val = cub.convert(fieldvalue, fieldlist[j].getType());
507                 fieldlist[j].set(object, val);
508             }
509             list.add(object);
510         }
511         return list;
512     }
513     //$in 查询
514     public List<Object> findBeanByIn(String tablename,Class clazz,String field,Object...objects) 
515             throws Exception{
516         DBCollection col = getMongodb().getCollection(tablename);
517         BasicDBObject basic = new BasicDBObject();
518         DBCursor cursor = null;
519         Map<String,Object> mapfield = new HashMap<String,Object>();
520         Object object = clazz.newInstance();
521         ConvertUtilsBean cub = new ConvertUtilsBean(); 
522         BasicDBObject basicappend = new BasicDBObject();
523         basicappend.append("$in", objects);
524         basic.put(field, basicappend);
525         cursor = col.find(basic);
526         List<Object> list = new ArrayList<Object>();
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<String, Object>) cursor.next();
534             for(int i=0;i<fieldlist.length;i++){
535             Field fi = fieldlist[i];
536             String fieldname = fi.getName();
537             if(!mapfield.containsKey(fieldname)){
538                 continue;
539             }
540             Object fieldvalue =http://www.mamicode.com/ mapfield.get(fieldname);
541             Object val = cub.convert(fieldvalue, fi.getType());
542             fi.set(object, val);
543         }
544         list.add(object);
545         }
546         return list;
547     }
548     //Order By 排序查询
549     public List<Object> findBeanBySort(String tablename,Class clazz,String param,int num)
550             throws Exception{
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<String,Object> map = new HashMap<String,Object>();
558         Field[] field = clsMap.get(clazz.getName());
559         Object value = http://www.mamicode.com/null;
560         Object val = null;
561         BasicDBObject basic = new BasicDBObject();
562         ConvertUtilsBean cub = new ConvertUtilsBean();
563         List<Object> list = new ArrayList<Object>();
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<String, Object>) cursor.next();
572             for(int j=0;j<field.length;j++){
573                 String name = field[j].getName();
574                 Field fi = field[j];
575                 if(map.containsKey(name)){
576                     value =http://www.mamicode.com/ map.get(name);
577                     val = cub.convert(value, fi.getType());
578                     fi.set(object, val);
579                 }
580             }
581             list.add(object);
582         }
583         return list;
584     }
585     //分页查询
586     public List<Object> findBeanByPage(String tablename,Class clazz,int size,int page)
587             throws Exception{
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<String,Object> map = new HashMap<String,Object>();
595         Field[] field = clsMap.get(clazz.getName());
596         Object value = http://www.mamicode.com/null;
597         Object val = null;
598         BasicDBObject basic = new BasicDBObject();
599         ConvertUtilsBean cub = new ConvertUtilsBean();
600         List<Object> list = new ArrayList<Object>();
601         if(field == null){
602             field = clazz.getDeclaredFields();
603             clsMap.put(clazz.getName(), field);
604         }
605         cursor = col.find().skip((page-1)*size).sort(new BasicDBObject()).limit(size);
606         while(cursor.hasNext()){
607             map = (Map<String, Object>) cursor.next();
608             for(int j=0;j<field.length;j++){
609                 String name = field[j].getName();
610                 Field fi = field[j];
611                 if(map.containsKey(name)){
612                     value =http://www.mamicode.com/ map.get(name);
613                     val = cub.convert(value, fi.getType());
614                     fi.set(object, val);
615                 }
616             }
617             list.add(object);
618         }
619         return list;
620     }
621     //Like模糊查询
622     public List<Object> findBeanByLike(String tablename,Class clazz,String fieldname,Object param)
623             throws Exception{
624         Object object = clazz.newInstance();
625         DBCollection col = getMongodb().getCollection(tablename);
626         DBCursor cursor = null;
627         Map<String,Object> map = new HashMap<String,Object>();
628         Field[] field = clsMap.get(clazz.getName());
629         BasicDBObject basic = new BasicDBObject();
630         ConvertUtilsBean cub = new ConvertUtilsBean();
631         List<Object> list = new ArrayList<Object>();
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<String, Object>) cursor.next();
649             for(int i=0;i<field.length;i++){
650                 String name = field[i].getName();
651                 if(!map.containsKey(name)){
652                     continue;
653                 }
654                 Object fieldvalue =http://www.mamicode.com/ map.get(fieldname);
655                 Object val = cub.convert(fieldvalue, field[i].getType());
656                 field[i].set(object, val);
657             }
658             list.add(object);
659         }
660         return list;
661     }
662     //返回查询的部分字段
663     public List<Object> findBeanColumn(String tablename,Class clazz,String[] fields,Map<String,Map<String,Object>> map) 
664             throws Exception{
665         DBCollection col = getMongodb().getCollection(tablename);
666         BasicDBObject basic = new BasicDBObject();
667         Object object = clazz.newInstance();
668         DBCursor cursor = null;
669         List<Object> list = new ArrayList<Object>();
670         Map<String,Object> map1 = new HashMap<String,Object>();
671         ConvertUtilsBean cub = new ConvertUtilsBean();
672         Field[] fieldlist = clsMap.get(clazz.getName());
673         BasicDBObject projection = new BasicDBObject();
674         for(int k=0;k<fields.length;k++){
675             projection.append(fields[k], true);
676         }
677         for(Entry<String,Map<String,Object>> entry:map.entrySet()){
678             String mapname = entry.getKey();
679             Map<String,Object> map2 = entry.getValue();
680             BasicDBObject basicappend = new BasicDBObject();
681             for(Entry<String,Object> entry1:map2.entrySet()){
682                 String map2name = entry1.getKey();
683                 Object map2value =http://www.mamicode.com/ 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<String, Object>) cursor.next();
698             for(int i=0;i<fieldlist.length;i++){
699                 String fieldname = fieldlist[i].getName();
700                 if(!map1.containsKey(fieldname)){
701                     continue;
702                 }
703                 Object fieldvalue =http://www.mamicode.com/ map1.get(fieldname);
704                 Object val = cub.convert(fieldvalue, fieldlist[i].getType());
705                 fieldlist[i].set(object, val);
706             }
707             list.add(object);
708         }
709         return list;
710     }
711     
712     
713     /*聚合操作*/
714     //count
715     public int objectcount(String tablenae, Map<String,Object> map){
716         DBCollection col = getMongodb().getCollection(tablenae);
717         BasicDBObject basic = new BasicDBObject();
718         for(Entry<String,Object> entry:map.entrySet()){
719             String name = entry.getKey();
720             Object value =http://www.mamicode.com/ entry.getValue();
721             basic.put(name, value);
722         }
723         int count = col.find(basic).count();
724         return count;
725     }
726     //Max与Min
727     public Map<String,Object> maxObject(String tablenae, String field){
728         DBCollection col = getMongodb().getCollection(tablenae);
729         BasicDBObject basic = new BasicDBObject();
730         basic.put(field, true);
731         DBCursor cursor = null;
732         Map<String,Object> map = new HashMap<String,Object>();
733         cursor = col.find().max(basic);
734         while(cursor.hasNext()){
735             map = (Map<String, Object>) cursor.next();
736         }
737         return map;
738     }
739     //Sum
740     public List<Map<String,Object>> sumObject(String tablename,String field,String field1){
741         DBCollection col = getMongodb().getCollection(tablename);
742         List<DBObject> list = new ArrayList<DBObject>();
743         BasicDBObject group = new BasicDBObject();
744         BasicDBObject sexdb = new BasicDBObject();
745         BasicDBObject agesum = new BasicDBObject();
746         Map<String,Object> map = new HashMap<String,Object>();
747         List<Map<String,Object>> listmap = new ArrayList<Map<String,Object>>();
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<String, Object>) cursor.next();
756             listmap.add(map);
757         }
758         return listmap;
759     }
760     //Avg
761     public List<Map<String,Object>> avgObject(String tablename,String field,String field1){
762         DBCollection col = getMongodb().getCollection(tablename);
763         DBCursor cursor = null;
764         BasicDBObject avgobject = new BasicDBObject();
765         BasicDBObject object = new BasicDBObject();
766         BasicDBObject basic = new BasicDBObject();
767         avgobject.append("$avg", "$"+field);
768         object.append("avg", avgobject);
769         object.append(field1, "$"+field1);
770         List<DBObject> list = new ArrayList<DBObject>();
771         Map<String,Object> map = new HashMap<String,Object>();
772         List<Map<String,Object>> listmap = new ArrayList<Map<String,Object>>();
773         list.add(object);
774         cursor = (DBCursor) col.aggregate(list, AggregationOptions.builder().allowDiskUse(true).build());
775         while(cursor.hasNext()){
776             map = (Map<String, Object>) cursor.next();
777             listmap.add(map);
778         }
779         return listmap;
780     }
781     
782 }

 

java对mongodb数据库进行数据操作