자바 에 서 는 mongodb 의 aggregate 취 합 조 회 를 사용 합 니 다.

원본 링크:http://www.cnblogs.com/timeout/p/10145646.html
우선, 우 리 는 데이터베이스 에서 몬 godb 의 집합 조 회 는 이렇게 쓰 여 있다.
db.getCollection('parking_record').aggregate(
        {$match : {"appId" : "2e1800b22ae70600", "leaveTime" : {"$gt" : ISODate("2017-07-12T00:00:00"), "$lt" : ISODate("2017-07-13T00:00:00")}}},
        {$group : {"_id" : "$leaveMethod", "count" : {$sum : 1}}},
        {$sort : {"_id" : 1}}
    )

자바 류 에 서 는 어떻게 해 야 합 니까?이것 은 내 가 쓴 그 중의 한 방법 이다.
(우선 mongodb 의 자바 드라이버 mongo - java - driver - 3.2.2. jar 를 가 져 옵 니 다)
/**
	 *           
	 * @param app_id   ID
	 * @param beginDate     
	 * @param endDate     
	 * @return {"ManualLeave":2,"AutoLeave":4}
	 * @throws Exception
	 */
	public String aggregateLeaveMethodByDate(String app_id, Date beginDate, Date endDate) throws Exception {
		MongoCollection collection = PluginMongo.instance().getDatabase().getCollection(MongoCollectionName.PARKING_RECORD);
		Document sub_match = new Document();
		sub_match.put("appId", app_id);
		sub_match.put("leaveTime", new Document("$gt", beginDate).append("$lt", endDate));
		
		Document sub_group = new Document();
		sub_group.put("_id", "$leaveMethod");
		sub_group.put("count", new Document("$sum", 1));
		
		Document match = new Document("$match", sub_match);
		Document group = new Document("$group", sub_group);
		Document sort = new Document("$sort", new Document("_id", 1));
		
		List aggregateList = new ArrayList();
		aggregateList.add(match);
		aggregateList.add(group);
		aggregateList.add(sort);
		
		JSONObject ret_obj = new JSONObject();
		AggregateIterable resultset = collection.aggregate(aggregateList);
		MongoCursor cursor = resultset.iterator();
		
		try {
			while(cursor.hasNext()) {
				Document item_doc = cursor.next();
				int leaveMethod = item_doc.getInteger("_id", 0);
				int count = item_doc.getInteger("count", 0);
				
				LeaveMethodEnum leaveMethodVal = LeaveMethodEnum.fromType(leaveMethod);
				ret_obj.put(leaveMethodVal.name(), count);
			}
		} finally {
			cursor.close();
		}
		
		return ret_obj.toJSONString();
	}

위의 것 은 match, group 등 몇 가지 상용, procject, limit 등 과 유사 하 므 로 위의 것 을 참고 할 수 있 습 니 다.
aggregate 에 관 한 sql 지식 은 초보 튜 토리 얼 을 참고 할 수 있 습 니 다.http://www.runoob.com/mongodb/mongodb-aggregate.html
다음으로 전송:https://www.cnblogs.com/timeout/p/10145646.html

좋은 웹페이지 즐겨찾기