跳至主要内容

理解聚合框架

What is the Aggregation Framework?

Aggregation Framework(聚合框架)是 MongoDB 讀取資料的方法之一,
可針對讀取的資料做許多操作,非常適合分析或計算數據。

聚合框架彷彿為資料建立了管道(Pipeline)。使用者從資料庫中找尋資料時,
就好比將資料庫中所有資料送入管道,資料在管道中會經過數個 Stage,
每個 Stage 可對資料進行篩選、群組化、轉換、排序等處理,最後以使用者想要的格式輸出資料。

Aggregation Framework: Pipeline 示意圖

Understanding the Aggregation Framework

使用 aggregate() 即可執行聚合操作,此時傳入的引數為一陣列,此陣列猶如 Pipeline,
其元素由 Document 物件組成,每個物件都是一個 Stage。

Aggregation Framework 指令格式
db.collection_name.aggregate([
{ $stage1: {} },
{ $stage2: {} },...
])
Aggregation Framework 指令範例
db.collection_name.aggregate([
# Stage 1:篩選資料,找出 field1 的值為 value1 的資料
{ $match: { field1: value1 } },
# Stage 2:資料群組化,將 field2.property1 的值相同的資料整合為相同群組,並賦予欄位別名,
# 並且以 alias2 顯示群組內的資料筆數。
{ $group: { _id: { alias1: "$field2.property1" }, alias2: { $sum: 1 } } },
# Stage 3:資料排序,以 alias2 的值為排序依據,做 DESC 排序。
{ $sort: { alias2: -1 } },
])
提示

只要是有意義的操作,不必刻意限制 Stage 的數量,
同一 Pipeline 當中也可能重複設定相同類型的 Stage(例如 $project)。
同樣的,每個 Stage 處理資料的程序也可以極其繁複。