MongoDB 聚合

aggregate() 聚合管道:$match 过滤、$group 分组、$sum/$avg 计算等阶段依次处理文档流。

Intermediate
Key PointsMongoDB,aggregate,聚合管道,$match,$group,$sum

讲解

aggregate() 聚合管道:$match 过滤、$group 分组、$sum/$avg 计算等阶段依次处理文档流。

示例

JavaScript
db.site.aggregate([
  { $match: { alexa: { $gt: 0 } } },
  { $group: { _id: null, total: { $sum: "$alexa" }, avg: { $avg: "$alexa" } } }
])
Output
{ _id: null, total: 4723, avg: 1180.75 }
阶段作用
$match过滤文档(尽量放前面以利用索引)
$group按 _id 分组聚合
$project挑选/重命名字段
$sort / $limit / $skip排序与分页
$unwind拆平数组,一条元素一行

Friends & Partners