자바 에 서 는 mongodb 의 aggregate 취 합 조 회 를 사용 합 니 다.
우선, 우 리 는 데이터베이스 에서 몬 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
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.