zoukankan      html  css  js  c++  java
  • Java中使用mongodb的aggregate聚合查询

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

  • 相关阅读:
    Atom | 编辑器Atom的使用小结
    离散数学 | ∅ 与 {∅} 出现在离散数学幂集合中
    Excel | 如何用Excel实现证件照底色调换
    Awesome图标 | 如何在某些编辑软件中使用Font Awesome字体图标
    将SSH的秘钥每次输入的密码去掉
    用canvas 画一个水位波纹上升下降的进度球
    解决Enter passphrase for key '/Users/mac/.ssh/id_rsa':的问题
    vue 注册全局过滤器
    解决vue的父组件打开子组件弹窗只走一次mounted的问题
    forEach终止循环的方法
  • 原文地址:https://www.cnblogs.com/timeout/p/10145646.html
Copyright © 2011-2022 走看看