蓝色天空.知识 · 实践 · 创造
我的收藏
MongoDB 教程目录 49章
MongoDB / LEARN BY DOING

MongoDB 聚合

系统梳理 MongoDB aggregate() 聚合框架、八种分组累加表达式与聚合管道阶段($project、$match、$skip、$limit、$unwind、$group、$sort、$geoNear),并通过离线 Python 管道引擎实测验证。

学完这一章,你能够

  • 系统梳理 MongoDB aggregate() 聚合框架、八种分组累加表达式与聚合管道阶段($project、$match、$skip、$limit、$unwind、$group、$sort、$geoNear),并通过离线 Python 管道引擎实测验证。

aggregate() 聚合基础与分组计数示例

MongoDB 的聚合框架(Aggregation Framework)用于对集合中的文档执行分组统计、求和、求均值与结构变换,返回计算后的汇总结果,在功能定位上类似关系型 SQL 中的 `GROUP BY` 与 `COUNT(*)` 统计查询。

聚合查询通过集合的 `db.COLLECTION_NAME.aggregate(pipeline)` 方法发起,现代 MongoDB(3.6+ 与 `mongosh`)要求传入阶段文档数组并返回游标直接迭代结果文档(早期 2.x 版本返回包含 `result` 数组与 `ok: 1` 的包装对象)。

以包含 3 篇教程文档的 `mycol` 集合为例(两位作者 `devdocs.example` 与 `Neo4j` 分别撰写 2 篇与 1 篇),执行 `db.mycol.aggregate([{$group: {_id: "$by_user", num_tutorial: {$sum: 1}}}])` 会按 `by_user` 字段分组并累加文档数,语义等价于 `SELECT by_user, COUNT(*) FROM mycol GROUP BY by_user`。离线管道验证脚本精确产出 `Neo4j: 1` 与 `devdocs.example: 2`,同时对 `$sum`、`$avg`、`$min`、`$max`、`$push`、`$addToSet`、`$first`、`$last` 八种分组累加器逐一核验。

聚合管道概念与常用阶段操作符

聚合管道借鉴了 Unix/Linux 命令行管道的思想:文档流依次经过多个处理阶段,前一阶段的输出直接作为下一阶段的输入,同一类阶段也可以在管道中多次复用。阶段内部使用的表达式本身是无状态的,仅依据当前流经的文档字段计算输出值。

MongoDB 聚合框架最常用的核心阶段包括:`$project`(筛选、重命名或派生字段与嵌套结构)、`$match`(沿用标准查询语法过滤文档,建议尽量前置以利用索引)、`$limit`(限制输出文档上限)、`$skip`(跳过前若干条文档)、`$unwind`(将数组字段拆分为多条单值文档)、`$group`(按指定键分组统计)、`$sort`(对中间结果排序)以及 `$geoNear`(按地理空间距离由近到远输出有序文档)。

在实际组合中,`$project: {title: 1, author: 1}` 默认仍会保留 `_id` 字段,若要隐藏 `_id` 必须显式声明 `_id: 0`;将 `$match: {score: {$gt: 70, $lte: 90}}` 串联 `$group: {_id: null, count: {$sum: 1}}` 可只统计指定分数区间的记录数(离线实测 6 篇样本文档命中 4 篇);在管道中加入 `$skip: 5` 则会丢弃前 5 篇文档仅向后传递剩余文档。注意在现代版本中应将单阶段也包裹在数组 `[...]` 内传入 `aggregate()`。

MongoDB $group 常用累加聚合表达式对照

表达式描述实例
$sum计算分组内指定数值字段或常量的总和。db.mycol.aggregate([{$group: {_id: "$by_user", total_likes: {$sum: "$likes"}}}])
$avg计算分组内指定数值字段的算术平均值。db.mycol.aggregate([{$group: {_id: "$by_user", avg_likes: {$avg: "$likes"}}}])
$min获取分组内所有文档对应字段的最小值。db.mycol.aggregate([{$group: {_id: "$by_user", min_likes: {$min: "$likes"}}}])
$max获取分组内所有文档对应字段的最大值。db.mycol.aggregate([{$group: {_id: "$by_user", max_likes: {$max: "$likes"}}}])
$push将分组内每条文档的字段值按顺序追加到结果数组中(保留重复值)。db.mycol.aggregate([{$group: {_id: "$by_user", urls: {$push: "$url"}}}])
$addToSet将字段值收集到数组中并自动去重,已存在的值不会重复写入。db.mycol.aggregate([{$group: {_id: "$by_user", unique_urls: {$addToSet: "$url"}}}])
$first按输入文档流顺序获取分组内第一条文档的指定字段值(通常配合前置 $sort)。db.mycol.aggregate([{$group: {_id: "$by_user", first_url: {$first: "$url"}}}])
$last按输入文档流顺序获取分组内最后一条文档的指定字段值(通常配合前置 $sort)。db.mycol.aggregate([{$group: {_id: "$by_user", last_url: {$last: "$url"}}}])

离线 Python 聚合管道验证 $group 八大累加器与 $project/$match/$skip 串联

含完整源码 · 280 行
展开查看收起
python
"""Offline MongoDB aggregation pipeline verifier (no live mongod required)."""
from collections import defaultdict
import json

VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"


def eval_match(doc, cond):
    for field, rule in cond.items():
        val = doc.get(field)
        if isinstance(rule, dict):
            for op, target in rule.items():
                if op == "$gt" and not (val is not None and val > target):
                    return False
                if op == "$gte" and not (val is not None and val >= target):
                    return False
                if op == "$lt" and not (val is not None and val < target):
                    return False
                if op == "$lte" and not (val is not None and val <= target):
                    return False
                if op == "$eq" and val != target:
                    return False
        elif val != rule:
            return False
    return True


def eval_expr(doc, expr):
    if isinstance(expr, str) and expr.startswith("$"):
        return doc.get(expr[1:])
    return expr


def run_pipeline(docs, pipeline):
    current = [dict(d) for d in docs]
    for stage in pipeline:
        (op, spec), = stage.items()
        if op == "$match":
            current = [d for d in current if eval_match(d, spec)]
        elif op == "$project":
            include_id = spec.get("_id", 1) != 0
            out = []
            for d in current:
                row = {}
                if include_id and "_id" in d:
                    row["_id"] = d["_id"]
                for k, v in spec.items():
                    if k == "_id":
                        continue
                    if v == 1 and k in d:
                        row[k] = d[k]
                out.append(row)
            current = out
        elif op == "$unwind":
            field = spec[1:] if spec.startswith("$") else spec
            out = []
            for d in current:
                arr = d.get(field, [])
                if isinstance(arr, list):
                    for item in arr:
                        copy_doc = dict(d)
                        copy_doc[field] = item
                        out.append(copy_doc)
            current = out
        elif op == "$group":
            key_expr = spec["_id"]
            groups = defaultdict(list)
            order = []
            for d in current:
                gk = None if key_expr is None else eval_expr(d, key_expr)
                if gk not in groups:
                    order.append(gk)
                groups[gk].append(d)
            out = []
            for gk in order:
                items = groups[gk]
                row = {"_id": gk}
                for out_field, acc in spec.items():
                    if out_field == "_id":
                        continue
                    (acc_op, acc_arg), = acc.items()
                    vals = [eval_expr(x, acc_arg) for x in items]
                    if acc_op == "$sum":
                        row[out_field] = sum(vals)
                    elif acc_op == "$avg":
                        row[out_field] = sum(vals) / len(vals)
                    elif acc_op == "$min":
                        row[out_field] = min(vals)
                    elif acc_op == "$max":
                        row[out_field] = max(vals)
                    elif acc_op == "$push":
                        row[out_field] = list(vals)
                    elif acc_op == "$addToSet":
                        seen = []
                        for v in vals:
                            if v not in seen:
                                seen.append(v)
                        row[out_field] = seen
                    elif acc_op == "$first":
                        row[out_field] = vals[0]
                    elif acc_op == "$last":
                        row[out_field] = vals[-1]
                out.append(row)
            current = out
        elif op == "$sort":
            for field, direction in reversed(list(spec.items())):
                current.sort(key=lambda d, f=field: d.get(f), reverse=(direction == -1))
        elif op == "$skip":
            current = current[spec:]
        elif op == "$limit":
            current = current[:spec]
        else:
            raise ValueError(f"Unsupported stage: {op}")
    return current


def main():
    mycol = [
        {
            "_id": "7df78ad8902c",
            "title": "MongoDB Overview",
            "description": "MongoDB is no sql database",
            "by_user": "devdocs.example",
            "url": "https://devdocs.example/mongodb",
            "tags": ["mongodb", "database", "NoSQL"],
            "likes": 100,
        },
        {
            "_id": "7df78ad8902d",
            "title": "NoSQL Overview",
            "description": "No sql database is very fast",
            "by_user": "devdocs.example",
            "url": "https://devdocs.example/mongodb",
            "tags": ["mongodb", "database", "NoSQL"],
            "likes": 10,
        },
        {
            "_id": "7df78ad8902e",
            "title": "Neo4j Overview",
            "description": "Neo4j is no sql database",
            "by_user": "Neo4j",
            "url": "https://neo4j.example/docs",
            "tags": ["neo4j", "database", "NoSQL"],
            "likes": 750,
        },
    ]

    # Case 1: $group count per by_user (SQL GROUP BY equivalent)
    c1_actual = run_pipeline(
        mycol,
        [
            {"$group": {"_id": "$by_user", "num_tutorial": {"$sum": 1}}},
            {"$sort": {"_id": 1}},
        ],
    )
    c1_expected = [
        {"_id": "Neo4j", "num_tutorial": 1},
        {"_id": "devdocs.example", "num_tutorial": 2},
    ]

    # Case 2: All 8 group accumulators ($sum, $avg, $min, $max, $push, $addToSet, $first, $last)
    acc_docs = [
        {"by_user": "devdocs.example", "likes": 100, "url": "https://devdocs.example/a"},
        {"by_user": "devdocs.example", "likes": 10, "url": "https://devdocs.example/a"},
        {"by_user": "devdocs.example", "likes": 40, "url": "https://devdocs.example/b"},
    ]
    c2_actual = run_pipeline(
        acc_docs,
        [
            {
                "$group": {
                    "_id": "$by_user",
                    "sum_likes": {"$sum": "$likes"},
                    "avg_likes": {"$avg": "$likes"},
                    "min_likes": {"$min": "$likes"},
                    "max_likes": {"$max": "$likes"},
                    "pushed_urls": {"$push": "$url"},
                    "unique_urls": {"$addToSet": "$url"},
                    "first_url": {"$first": "$url"},
                    "last_url": {"$last": "$url"},
                }
            }
        ],
    )[0]
    c2_expected = {
        "_id": "devdocs.example",
        "sum_likes": 150,
        "avg_likes": 50.0,
        "min_likes": 10,
        "max_likes": 100,
        "pushed_urls": [
            "https://devdocs.example/a",
            "https://devdocs.example/a",
            "https://devdocs.example/b",
        ],
        "unique_urls": [
            "https://devdocs.example/a",
            "https://devdocs.example/b",
        ],
        "first_url": "https://devdocs.example/a",
        "last_url": "https://devdocs.example/b",
    }

    # Case 3: $project with default _id and explicit _id: 0
    articles = [
        {"_id": 1, "title": "Intro", "author": "Alice", "score": 65},
        {"_id": 2, "title": "Pipelines", "author": "Bob", "score": 78},
        {"_id": 3, "title": "Indexes", "author": "Cara", "score": 90},
        {"_id": 4, "title": "Sharding", "author": "Dan", "score": 95},
        {"_id": 5, "title": "GridFS", "author": "Eva", "score": 82},
        {"_id": 6, "title": "Capped", "author": "Fay", "score": 71},
    ]
    with_id = run_pipeline(articles[:1], [{"$project": {"title": 1, "author": 1}}])[0]
    without_id = run_pipeline(articles[:1], [{"$project": {"_id": 0, "title": 1, "author": 1}}])[0]
    c3_actual = {"with_id_keys": sorted(with_id.keys()), "without_id": without_id}
    c3_expected = {
        "with_id_keys": ["_id", "author", "title"],
        "without_id": {"title": "Intro", "author": "Alice"},
    }

    # Case 4: $match (70 < score <= 90) -> $group count, plus $skip & $limit & $unwind
    matched_count = run_pipeline(
        articles,
        [
            {"$match": {"score": {"$gt": 70, "$lte": 90}}},
            {"$group": {"_id": None, "count": {"$sum": 1}}},
        ],
    )[0]["count"]
    skipped_titles = [
        d["title"]
        for d in run_pipeline(articles, [{"$skip": 5}, {"$limit": 2}])
    ]
    unwound_tags = len(run_pipeline(mycol[:1], [{"$unwind": "$tags"}]))
    c4_actual = {
        "matched_70_to_90": matched_count,
        "after_skip_5": skipped_titles,
        "unwound_tag_docs": unwound_tags,
    }
    c4_expected = {
        "matched_70_to_90": 4,
        "after_skip_5": ["Capped"],
        "unwound_tag_docs": 3,
    }

    cases = [
        {
            "name": "group_by_user_count",
            "summary": "Verify $group + $sum: 1 counts documents per author like SQL GROUP BY.",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "group_accumulators_all_eight",
            "summary": "Verify $sum, $avg, $min, $max, $push, $addToSet, $first, and $last accumulators.",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
        {
            "name": "project_include_and_exclude_id",
            "summary": "Verify $project keeps _id by default and omits _id when _id: 0 is specified.",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_expected,
        },
        {
            "name": "match_skip_limit_unwind_pipeline",
            "summary": "Verify chained $match (70 < score <= 90) + $group, $skip: 5, $limit, and $unwind.",
            "expected": c4_expected,
            "actual": c4_actual,
            "passed": c4_actual == c4_expected,
        },
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
在离线验证脚本中确认按作者分组计数、八大累加器输出、$project 保留/排除 _id 以及 $match+$group+$skip+$unwind 管道结果全部通过。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1729.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:MongoDB

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1729.zip

下载课程关联工程包:MongoDB

课程关联工程包(登记关联49章) · 含当前章节或实例 · mbskycom202612a1732.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

因为集合文档的自然扫描顺序并无业务保证,前置 $sort 可以明确输入流顺序,使 $first/$last 稳定提取目标首尾记录。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习