package com.coship.cdc.server.web; import java.io.File; import java.io.IOException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.StringUtils; import com.mongodb.BasicDBList; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.Mongo; import com.mongodb.gridfs.GridFS; import com.mongodb.gridfs.GridFSDBFile; import com.mongodb.gridfs.GridFSInputFile; /** * * <一句话功能描述> * <p> * 作用 mongodb 在JAVA常用一些常用用法汇总 * <p> * @author 钟少卿 908342 * @version [<版本号>, 2013-11-27 下午02:42:47] * @see [<相关类>/<相关方法>] * @since [<CDC>/<SERVER>] */ public class MongoCRUD { /** * 数据库连接 */ public static DBCollection getCollection() throws UnknownHostException{ Mongo mongo3 = new Mongo("127.0.0.1",27017); DB db = mongo3.getDB("cdc"); DBCollection d = db.getCollection("BusinessInfoDto"); return d; } /** * in查询\大于符号 */ public void findByIn(DBCollection d){ BasicDBObject query =new BasicDBObject(); List list =new ArrayList(); list.add("3"); list.add("4"); query.put("Type", new BasicDBObject("$in", list)); query.put("ype", new BasicDBObject("$gt", "1")); //and的关系 DBCursor cur = d.find(query); while (cur.hasNext()) { System.out.println("in:"+cur.next()); } } /** * 应用程序中的片段 * 关于like 查询 用法 和 分页使用 * @param faultQuery * @param page * @return */ /* public List<CompanyDto> getQuery(FaultQuery faultQuery, PageQuery page) { Query<CompanyDto> query = createQuery(); // query.criteria("messageOrigin").equal(faultQuery.getSrc()); if (faultQuery != null) { if (!StringUtils.isEmpty(faultQuery.getCastName())) { Pattern pattern = Pattern.compile(".*" + faultQuery.getCastName() + ".*", Pattern.CASE_INSENSITIVE); query.filter("castName", pattern); } if (!StringUtils.isEmpty(faultQuery.getCastNum())) { Pattern pattern = Pattern.compile(".*" + faultQuery.getCastNum() + ".*", Pattern.CASE_INSENSITIVE); query.filter("castNum", pattern); } if (!StringUtils.isEmpty(faultQuery.getCastDistrict())) { Pattern pattern = Pattern.compile(".*" + faultQuery.getCastDistrict() + ".*", Pattern.CASE_INSENSITIVE); query.filter("castDistrict", pattern); } } if (page != null) { if (page.getRecordCount() == 0) { long count = count(query); page.setRecordCount((int) count); } faultQuery.setPageSize(page.getPageSize()); faultQuery.setBeginIndex(page.getBeginIndex()); query.skip(page.getBeginIndex());// skip相当于从那条记录开始 query.limit(page.getPageSize());// // 从skip开始,取多少条记录 } return find(query).asList(); }*/ /** * 程序中使用 多条件查询写法 */ /* public static void findByFilter(){ OrmCollDao dao = OrmCollDao.getInstance(); //filter之间以and连接 // Query query = dao.createQuery().filter("age >",1); query.filter("userId <=", 10010); query.filter("male =", true); query.filter("embedded_doc.type =", "type_str"); query.filter("refList exists ", true); List<OrmColl> list = dao.find(query).asList(); System.out.println("list.size:"+list.size()); for(int i=0;i<list.size();i++){ displayObj(list.get(i)); } } */ /** * Fluent查询方式 ,OR条件查询 */ /* public static void orQuery(){ OrmCollDao dao = OrmCollDao.getInstance(); Query<OrmColl> query = dao.createQuery(); query.or( query.criteria("userId").equal(10010), query.criteria("age").greaterThan(1) ); List<OrmColl> list = dao.find(query).asList(); System.out.println("list.size:"+list.size()); for(int i=0;i<list.size();i++){ displayObj(list.get(i)); } } */ /** * count查询 */ public void count(DBCollection d){ BasicDBObject query =new BasicDBObject(); query.put("alarmThresholdType", "4"); long a = d.count(query); System.out.println("count:"+a); } /** * Count求和 */ /*public static void getCount(){ OrmCollDao dao = OrmCollDao.getInstance(); Query query = dao.createQuery().field("userId").greaterThanOrEq(10095); long count = dao.count(query); System.out.println(count); } */ /** * 单个删除 */ public void remove(DBCollection d){ BasicDBObject document =new BasicDBObject(); document.put("alarmThresholdType", 99); document.put("alarmThresholdType", 100); d.remove(document); //这样子只会将alarmThresholdType=100的删除。 } /** * 多个删除 */ public void removeMany(DBCollection d){ BasicDBObject query2 =new BasicDBObject(); List list =new ArrayList(); list.add(99); list.add(100); query2.put("alarmThresholdType", new BasicDBObject("$in", list)); d.remove(query2); } /** * 保存图片信息 */ public void savePhoto(){ Mongo mongo3 = null; try { mongo3 = new Mongo("10.9.219.7",27017); } catch (UnknownHostException e1) { e1.printStackTrace(); } DB db = mongo3.getDB("cdc"); String newFileName ="mkyong-java-image"; File imageFile =new File("c:\\111.bmp"); GridFS gfsPhoto =new GridFS(db, "photo"); GridFSInputFile gfsFile = null; try { gfsFile = gfsPhoto.createFile(imageFile); } catch (IOException e) { e.printStackTrace(); } gfsFile.setFilename(newFileName); gfsFile.save(); System.out.println("图片保存成功"); } /** * 输出图片属性信息 */ public void findPhoto(){ Mongo mongo3 = null; try { mongo3 = new Mongo("10.9.219.7",27017); } catch (UnknownHostException e1) { e1.printStackTrace(); } DB db = mongo3.getDB("cdc"); String newFileName ="mkyong-java-image"; GridFS gfsPhoto =new GridFS(db, "photo"); GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName); System.out.println("输出图片属性信息:"+imageForOutput); } /** * 从数据库中读取一张图片并另存 */ public void dbTodisk(){ Mongo mongo3 = null; try { mongo3 = new Mongo("10.9.219.7",27017); } catch (UnknownHostException e1) { e1.printStackTrace(); } DB db = mongo3.getDB("cdc"); String newFileName ="mkyong-java-image"; GridFS gfsPhoto =new GridFS(db, "photo"); GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName); String url = "c:\\JavaWebHostingNew.jpg"; try { imageForOutput.writeTo(url); } catch (IOException e) { e.printStackTrace(); } System.out.println("图片另存为成功,路径:"+url); } /***********************************************高级查询 分组 group 应用 *********************************************************/ /** * keyColumn : new String[]{"xxxName","xxxType"} <br> * condition : 查询条件 ,可为空<br> * initial : 分组统计初始变量,为空时自动为每列提供初始变量<br> * reduce : 记录处理function<br> * finalize : finalize函数,可为空 <br> */ public BasicDBList group(String[] keyColumn, DBObject condition, DBObject initial, String reduce, String finalize,DBCollection d) { // DBCollection coll = getCollection();//获得查询集合 DBObject key = new BasicDBObject(); for (int i = 0; i < keyColumn.length; i++) { key.put(keyColumn[i], true); } condition = (condition == null) ? new BasicDBObject() : condition; if (StringUtils.isEmpty(finalize)) { finalize = null; } if (initial == null) { //定义一些初始变量 initial = new BasicDBObject(); for (int i = 0; i < keyColumn.length; i++) { DBObject index = new BasicDBObject(); index.put("count", 0); index.put("sum", 0); index.put("max", 0); index.put("min", 0); index.put("avg", 0); index.put("self", ""); initial.put(keyColumn[i], index); } } BasicDBList resultList = (BasicDBList) d.group(key, condition, initial, reduce, finalize); return resultList; } //任务统计 /* @Action(value = "getTaskStatistic", results = { @Result(name = "success", type = "json", params = { "includeProperties", "jsonResult" }) })*/ /* public String getTaskStatistic() { DBObject initial = new BasicDBObject(); DBObject index = new BasicDBObject(); index.put("count", 0); index.put("taskStatus", ""); initial.put("taskStatus", index); String reduce = "function (doc, out) { " + " out.taskStatus.count = out.taskStatus.count+=1; " + " out.taskStatus.inspectStatus = doc.taskStatus;" + "}"; BasicDBList group = (BasicDBList) taskStatusService.group(new String[] { "taskStatus"}, null, initial, reduce, null); this.jsonResult = group.toString(); return SUCCESS; }*/ /** * 分组查询(求count、sum) */ public static void dogroup(DBCollection d){ DBObject key = new BasicDBObject(); key.put("businessCode", true); BasicDBObject cond = new BasicDBObject(); //可选的查询条件 /* DBObject index = new BasicDBObject(); index.put("count", 0); index.put("sum", 0); */ DBObject initial = new BasicDBObject(); initial.put("num", 0); String reduce = "function (doc, prev) { " + "prev.num ++;"+ "}"; String fn = null; BasicDBList ddd = (BasicDBList)d.group( key, //分组字段,即group by的字段 cond, //查询中where条件 initial,//初始化各字段的值 reduce,//每个分组都需要执行的Function fn//终结Funciton对结果进行最终的处理 ); System.out.println(ddd); } /*final List<String> targetTerms = Arrays.asList("dogs", "cats"); final Datastore ds = …. final DBCollection coll = ds.getCollection(Example.class); BasicDBObject key = new BasicDBObject("_id", true); BasicDBObject cond = new BasicDBObject(); cond.append("indices", new BasicDBObject("$in", targetTerms)); BasicDBObject initial = new BasicDBObject(); initial.append("score", 0); initial.append("targetTerms", targetTerms); String reduce = "function (obj, prev) { " + " for (i in prev.targetTerms) {" + " targetTerm = prev.targetTerms[i];"+ " for (j in obj.indices) {" + " var index = obj.indices[j];"+ " if (targetTerm === index) prev.score++;" + " }" + " }" + "}"; String fn = null; final BasicDBList group = (BasicDBList) coll.group(key, cond, initial, reduce, fn);*/ /*@Test public void testGroupBy() throws Exception { String reduce = "function(doc, aggr){" + " aggr.count += 1;" + " }"; Query query = Query.query(Criteria.where("age").exists(true)); DBObject result = mongoTemplate.getCollection("person").group(new BasicDBObject("age", 1), query.getQueryObject(), new BasicDBObject("count", 0), reduce); Map map = result.toMap(); System.out.println(map); for (Map.Entry o : map.entrySet()) { System.out.println(o.getKey() + " " + o.getValue()); } }*/ /** * 分组查询(求count、sum) */ public static void dogroup2(DBCollection d){ DBObject key = new BasicDBObject(); key.put("compObj.castName", true); BasicDBObject cond = new BasicDBObject(); //可选的查询条件 cond.put("$and","businessCode"); // cond.append("businessCode", new BasicDBObject("businessCode", "businessCode")); DBObject index = new BasicDBObject(); index.put("count", 0); index.put("castName", "castName"); DBObject initial = new BasicDBObject(); initial.put("num", 0); String reduce = "function (doc, prev) { " + "prev.num ++;"+ "}"; String fn = null; BasicDBList ddd = (BasicDBList)d.group( key, //分组字段,即group by的字段 cond, //查询中where条件 initial,//初始化各字段的值 reduce,//每个分组都需要执行的Function fn//终结Funciton对结果进行最终的处理 ); System.out.println(ddd); } public static void main(String[] args) throws UnknownHostException { DBCollection d =getCollection(); dogroup2(d); } }