譯者: 飛龍 來源: Aggregation
如果你需要從一個模型中擷取一些聚合值,你可以使用
Model.aggregate()
。下面通過一個例子來展示:
Person.aggregate({ surname: "Doe" }).min("age").max("age").get(function (err, min, max) {
console.log("The youngest Doe guy has %d years, while the oldest is %d", min, max);
});
可以傳遞一個含有屬性的
Array
來選擇僅僅保留一小部分屬性。方法也會接收一個
Object
來定義條件。
下面是一個展示如何使用
.groupBy()
的例子:
// 和 "select avg(weight), age from person where country='someCountry' group by age;" 相同
Person.aggregate(["age"], { country: "someCountry" }).avg("weight").groupBy("age").get(function (err, stats) {
// stats 是一個數組,每個記錄都有 'age' 和 'avg_weight' 屬性
});
基本的 .aggregate()
方法
.aggregate()
-
:你可以傳遞一個數值作為個數,或者兩個數值分别作為偏移和個數limit()
-
:和order()
相同Model.find().order()
額外的 .aggregate()
.aggregate()
-
min
-
max
-
avg
-
sum
-
(它有一個快捷方式 -count
)Model.count
有更多的聚合函數是依賴于驅動的(比如數學函數)。