Java操作Mongo(聚合函数)使用
2.1 插入(插入后数据库结构见最上方)
废话不多说 上代码(主要代码):
@Override public void addDocument(String identity, String applicationKey, List<Map<String, String>> list) { //创建一个连接,自带连接池效果 MongoClient mongoClient = MongoClients.create("mongodb://192.168.10.8:27017"); //操作一个数据库,如果数据库不存在,当您为该数据库首次存储数据时,会自动创建数据库。 MongoDatabase spitdbDatabase = mongoClient.getDatabase(applicationKey); //得到一个集合对象,如果集合不存在,当您为该数据库首次存储数据时,会自动创建集合。 MongoCollection<Document> collection = spitdbDatabase.getCollection(identity); //创建一个文档,参数可以接收键值对,也可以直接接收一个Map对象 //文档对象的本质是BSON类型,该类型对应java.util.Map;BSON数组对应的是java.util.List List<Document> documentList = MongoUtils.listForDocument(list); Map<String, List<Document>> map = new HashMap<>(); //int size = documentList.size(); double number = 10.0; int n = 1; String[] s; for (Document document : documentList) { String gmtTarget = document.get("gmtTarget") + ""; s = gmtTarget.split(" "); if (map.containsKey(s[0])) { if (map.get(s[0]).size() < number) { map.get(s[0]).add(document); } else { List<Document> documents = new ArrayList<>(); documents.add(document); map.put(s[0] + "." + n, documents); n++; } } else { List<Document> documents = new ArrayList<>(); documents.add(document); map.put(s[0], documents); } } FindIterable<Document> documents = collection.find(); Map<String, Object> map1 = new LinkedHashMap<>(); int val = 0; for (Document document1 : documents) { map1.put("_id" + "." + val, document1.get("_id")); val++; } for (String key : map.keySet()) { collectionDemo(map.get(key)); Document document = new Document(); //当数组在表中不存在时 就新建数组 if (documents == null || map1.containsValue(key) == false) { document.append("_id", key).append("gmtStart", map.get(key).get(0).get("gmtTarget")).append("gmtEnd", map.get(key).get(map.get(key).size() - 1).get("gmtTarget")) .append("count", map.get(key).size()).append("records", map.get(key)); collection.insertOne(document); } else { //若存在 则在原有对应数组后插入新数据 Document y2 = null; List<Document> list2 = map.get(key); for (int i = 0; i < map.get(key).size(); i++) { String gmtTarget = (String) map.get(key).get(i).get("gmtTarget"); String[] s1 = gmtTarget.split(" "); y2 = new Document("_id", s1[0]); } //在数组后加入新数据 若数据存在 则不会存入 Document update = new Document().append("$addToSet", new Document().append("records", new Document().append("$each", list2))); //获取数据的时间判断其所属数组 并将数据存入对应数组中 collection.updateMany(y2, update); FindIterable<Document> documents1 = collection.find(y2); ArrayList<Document> records = null; for (Document document1 : documents1) { //获取对应数组相关信息 records = (ArrayList<Document>) document1.get("records"); } //System.out.println(records); collectionDemo(records); //向新数组新增数据后数组对应参数随之改变 给各个参数分别赋值 Document update2 = new Document().append("$set", new Document().append("count", records.size()).append("gmtStart", records.get(0).get("gmtTarget")).append("gmtEnd", records.get(records.size() - 1).get("gmtTarget")).append("records", records)); collection.updateOne(y2, update2); } } //释放资源 mongoClient.close(); }
2.2 查询
废话不多说 上代码(主要代码):
@RequestMapping(value = "/findMongo", method = RequestMethod.POST) public ResponseMessage findMongo(Integer index, @RequestBody Map<String, String> map) { if (index == null || index < 1) { index = 1; } MongoClient mongoClient = new MongoClient(host, port); MongoDatabase db = mongoClient.getDatabase(map.get("applicationKey")); //MongoDatabase db = mongoClient.getDatabase("dgg8be05077d4890910ed2ce8b481"); //MongoCollection<Document> doc = db.getCollection(map.get("identity")); MongoCollection<Document> doc = db.getCollection(map.get("identity")); Page<Document> page = new Page<>(); Map<String, String> mapKey = new HashMap<>(); for (Map.Entry<String, String> entry : map.entrySet()) { if (StringUtils.isNotEmpty(entry.getValue())) { mapKey.put(entry.getKey(), entry.getValue()); } } String identity = mapKey.get("identity"); String applicationKey = mapKey.get("applicationKey"); //Query query = new Query(); //SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"); if (map != null && map.size() != 0 && !mapKey.isEmpty()) { // match(相当于 WHERE 或者 HAVING ) BasicDBObject query = new BasicDBObject(); List<BasicDBObject> list = new ArrayList<>(); for (Map.Entry<String, String> entry : mapKey.entrySet()) { String key = entry.getKey(); if (key.equals("identity") || key.equals("applicationKey") || key.equals("pageUrl")) { } else { String value = entry.getValue(); if (value.contains("~")) { String[] split = value.split("~"); String startTime = null; String endTime = null; try { startTime = split[0]; endTime = split[1]; } catch (Exception e) { e.printStackTrace(); } list.add(new BasicDBObject("records.gmtTarget", new BasicDBObject("$gte", startTime))); list.add(new BasicDBObject("records.gmtTarget", new BasicDBObject("$lte", endTime))); } else { list.add(new BasicDBObject(("records") + "." + key, value)); } } } if (list != null && list.size() > 0) { BasicDBObject[] array = new BasicDBObject[list.size()]; list.toArray(array); query.append("$and", array); BasicDBObject match = new BasicDBObject("$match", query); BasicDBObject unwind = new BasicDBObject("$unwind", "$records"); // BasicDBObject project = new BasicDBObject("$project", new BasicDBObject("count", new BasicDBObject("$size","$records"))); BasicDBObject project = new BasicDBObject("$project", new BasicDBObject("records", 1)); //sort(排序) BasicDBObject sort = new BasicDBObject("$sort", new BasicDBObject("count", -1));//1:正序,-1倒序 //skip(跳过前面多少条数据,分页时使用) //limt(只要前多少条数据,分页时使用) BasicDBObject limit = new BasicDBObject("$limit", 15); BasicDBObject skip = new BasicDBObject("$skip", 0); List<BasicDBObject> aggregateList = new ArrayList<>(); aggregateList.add(unwind); aggregateList.add(project); aggregateList.add(match); aggregateList.add(sort); aggregateList.add(limit); aggregateList.add(skip); AggregateIterable<Document> aggregate = mongoClient.getDatabase(applicationKey).getCollection(identity).aggregate(aggregateList); List<Document> list1 = new ArrayList<>(); int totalCount = 0; for (Document document : aggregate) { list1.add(document); if (list1 != null) { totalCount++; } int totalPage = totalCount % 15 == 0 ? totalCount / 15 : totalCount / 15 + 1; page.setStartIndex((index - 1) * 15); page.setTotalRecords(totalCount); page.setTotalPage(totalPage); page.setRecords(list1); } page.setCurrentPage(index); page.setPageSize(Page.DEFAULT_VALUE); return success(page); } else { FindIterable<Document> iter = doc.find().skip(0).limit(15); int totalCount = 0; Page<Document> page1 = new Page<>(); List<Document> list1 = new ArrayList<>(); for (Document document : iter) { MongoCursor<Document> iterator = iter.iterator(); iterator.next(); if (document.get("_id") != null) { totalCount++; } document.remove("_id"); Object records = document.get("records"); document.put("records", records); list1.add(document); page1.setCurrentPage(index); page1.setPageSize(Page.DEFAULT_VALUE); int totalPage = totalCount % 15 == 0 ? totalCount / 15 : totalCount / 15 + 1; page1.setStartIndex((index - 1) * 15); page1.setTotalRecords(totalCount); page1.setTotalPage(totalPage); page1.setRecords(list1); } return success(page1); } } else { FindIterable<Document> iter = doc.find().skip(0).limit(15); int totalCount = 0; Page<Document> page1 = new Page<>(); List<Document> list = new ArrayList<>(); for (Document document : iter) { MongoCursor<Document> iterator = iter.iterator(); iterator.next(); if (document.get("_id") != null) { totalCount++; } document.remove("_id"); Object records = document.get("records"); document.put("records", records); list.add(document); page1.setCurrentPage(index); page1.setPageSize(Page.DEFAULT_VALUE); int totalPage = totalCount % 15 == 0 ? totalCount / 15 : totalCount / 15 + 1; page1.setStartIndex((index - 1) * 15); page1.setTotalRecords(totalCount); page1.setTotalPage(totalPage); page1.setRecords(list); } return success(page1); } }