天天看點

mongoDB aggregate聚合分析

簡介

聚集操作實際上是對資料進行統計分析時使用的,簡單的說,可以了解為SQL中的聚合操作,MongoDB中的聚集操作是為了大資料分析做準備的,這裡簡單介紹一下聚集架構aggregate的使用。

管道模式聚集分析

MongoDB的聚合架構是參考UNIX上的管道指令實作的,資料通過一個多步驟的管道,每個步驟都會對資料進行加工處理,最後傳回需要的結果集。 

管道聚集是可以操作一個分片的集合的(The aggregation pipeline can operate on a sharded collection.) 

管道聚集在某一些階段可以利用索引提高性能,另外,管道聚集還有一個一個内部優化階段(後面管道聚集優化會講到)。

常見的管道操作符有如下:

操作符 說明
$match 過濾文檔
$limit 限制管道中檔案的資料
$skip 跳過指定的文檔數量
$sort 對所輸入的文檔進行排序
$group 對文檔進行分組後計算聚集結果
$out 輸出文檔到具體的集合中(必須是管道操作的最後一步)

與$group一起使用的聚集操符:

操作符 說明
$first 傳回group後的第一個值
$last 傳回group後的最後一個值
$max group後的最大值
$min group後的最小值
$avg group後的平均值
$sum group後求和

示例:

db.Collection.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

使用 new Document()對象來替代上面{“XXX”:”XXX”}條件

示例:

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();

       }