序章
集計操作は、実際にはデータの統計分析に使用されます。簡単に言うと、 SQLの集計操作として理解できます。MongoDBの集計操作は、ビッグ データ分析用に用意されています。ここでは、集計フレームワークである集計
MongoDBの集計フレームワークは、 UNIX上のパイプライン コマンドを参照して実装されており、データは複数ステップのパイプラインを通過し、各ステップでデータが処理され、最終的に必要な結果セットが返されます。
パイプライン集約は、断片化されたコレクションで操作できます (集約パイプラインは、シャード化されたコレクションで操作できます。)
パイプライン集約は、インデックスを使用して、特定の段階でのパフォーマンスを向上させることができます。さらに、パイプライン集約には、内部最適化ステージがあります (パイプライン集約の最適化については後ほど説明します) )。
一般的なパイプライン演算子は次のとおりです。
オペレーター |
説明する |
$match |
ドキュメントをフィルタリングする |
$limit |
パイプライン内のファイルのデータを制限する |
$スキップ |
指定された数のドキュメントをスキップします |
$sort |
入力した書類を並べ替える |
$グループ |
文書をグループ化して集計結果を計算する |
$out |
ドキュメントを特定のコレクションに出力します (パイプライン操作の最後のステップである必要があります) |
$ groupで使用される集計演算子:
オペレーター |
説明する |
$first |
グループの後の最初の値を返します |
$last |
グループの後の最後の値を返します |
$max |
グループ後の最大値 |
$分 |
グループ後の最小値 |
平均$ |
グループ後の平均 |
$sum |
グループ後の合計 |
例:
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}}},
{$ソート : {"_id" : 1}}
)
Java操作への統合
まずmongodbのJavaドライバー パッケージmongo-java-driver-3.2.2.jarをインポートします。
新しい 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();
}