mongo java aggregate_Java中使用mongodb的aggregate聚合查询

本文介绍了如何在Java中使用MongoDB的aggregate方法进行聚合查询,以统计特定日期范围内不同离场方式的数量。通过示例展示了如何构建$match、$group和$sort阶段的文档,并执行聚合操作获取结果。
摘要由CSDN通过智能技术生成

首先,我们在数据库中,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 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();

}上面的只有matche,group等几个常用,project,limit等类似,可以参考上面的。

aggregate的相关sql知识可以参考菜鸟教程:http://www.runoob.com/mongodb/mongodb-aggregate.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值