rmdir.cn

聚合管道更多阶段

聚合管道高级阶段速查

语法

db.collection.aggregate([{ <stage>: { ... } }, ...])

说明

除 $match/$group/$sort/$project/$lookup/$unwind 外,聚合管道还提供 $addFields 添加字段、$count 统计、$limit/$skip 分页、$out 输出到集合、$merge 合并结果、$facet 多路聚合、$bucket 分组分桶、$bucketAuto 自动分桶等强大阶段。

参数

  • $addFields

    添加新字段或覆盖已有字段(不影响原文档)

  • $count

    返回当前管道中文档总数,输出 { count: N }

  • $limit / $skip

    限制/跳过指定数量的文档

  • $out

    将聚合结果写入新集合(覆盖原有数据)

  • $merge

    将结果合并到已有集合(可指定合并策略)

  • $facet

    在同一组文档上并行执行多条管道

  • $bucket

    按自定义边界将文档分为桶

  • $bucketAuto

    自动按均匀分布分为指定数量的桶

  • $replaceRoot

    将嵌套文档提升为根文档

  • $sample

    随机抽取指定数量的文档

示例

$facet 多路聚合

一次查询同时获得多种统计

db.products.aggregate([{ $facet: { byCategory: [{ $group: { _id: "$category", count: { $sum: 1 } } }], priceRange: [{ $bucket: { groupBy: "$price", boundaries: [0,100,500,1000,5000], default: "other" } }], topRated: [{ $sort: { rating: -1 } }, { $limit: 10 }] } }])

$addFields 计算字段

添加计算字段

db.orders.aggregate([{ $addFields: { totalPrice: { $multiply: ["$price", "$qty"] }, discountedPrice: { $multiply: ["$price", 0.9] } } }])

$merge 合并结果

将统计结果写入目标集合

db.sales.aggregate([{ $group: { _id: "$category", total: { $sum: "$amount" } } }, { $merge: { into: "category_stats", on: "_id", whenMatched: "replace", whenNotMatched: "insert" } }])

$sample 随机抽样

随机获取 3 个文档

db.users.aggregate([{ $sample: { size: 3 } }])