首先,我们在数据库中,mongodb的聚合查询是这样写。
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}} )
在java类中,应该怎样呢?这是我写的其中一个方法。
(首先要导入mongodb的java驱动包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<Document> 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<Document> aggregateList = new ArrayList<Document>(); aggregateList.add(match); aggregateList.add(group); aggregateList.add(sort); JSONObject ret_obj = new JSONObject(); AggregateIterable<Document> resultset = collection.aggregate(aggregateList); MongoCursor<Document> 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(); }上面的只有matche,group等几个常用,project,limit等类似,可以参考上面的。
aggregate的相关sql知识可以参考菜鸟教程:http://www.runoob.com/mongodb/mongodb-aggregate.html