蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行单字段升降序、多字段组合排序、likes 降序投影与 sort->skip->limit 优先级验证

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-sort.py
explore-sort.py119 行
"""Offline MongoDB sort() single/compound fields & sort->skip->limit precedence verifier (Ch23 sort)."""
import json

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


def mongo_sort(docs: list, sort_spec: list[tuple[str, int]]) -> list:
    res = list(docs)
    for field, direction in reversed(sort_spec):
        res.sort(key=lambda d: d[field], reverse=(direction == -1))
    return res


USERS = [
    {"name": "Carol", "age": 30, "createdAt": "2026-01-10"},
    {"name": "Alice", "age": 25, "createdAt": "2026-03-01"},
    {"name": "Bob", "age": 25, "createdAt": "2026-05-15"},
    {"name": "David", "age": 35, "createdAt": "2026-02-20"},
]

COL = [
    {"_id": 1, "title": "PHP 教程", "likes": 200},
    {"_id": 2, "title": "Java 教程", "likes": 150},
    {"_id": 3, "title": "MongoDB 教程", "likes": 100},
]


def case_single_field_asc_and_desc():
    asc_ages = [d["age"] for d in mongo_sort(USERS, [("age", 1)])]
    desc_dates = [d["name"] for d in mongo_sort(USERS, [("createdAt", -1)])]
    actual = {"age_asc": asc_ages, "createdAt_desc_names": desc_dates}
    expected = {"age_asc": [25, 25, 30, 35], "createdAt_desc_names": ["Bob", "Alice", "David", "Carol"]}
    return {
        "name": "single_field_asc_and_desc",
        "summary": "验证 sort({age: 1}) 升序与 sort({createdAt: -1}) 降序单字段排序。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_multi_field_compound_sort():
    sorted_docs = mongo_sort(USERS, [("age", 1), ("createdAt", -1)])
    actual = [(d["name"], d["age"], d["createdAt"]) for d in sorted_docs]
    expected = [
        ["Bob", 25, "2026-05-15"],
        ["Alice", 25, "2026-03-01"],
        ["Carol", 30, "2026-01-10"],
        ["David", 35, "2026-02-20"],
    ]
    actual_list = [list(x) for x in actual]
    return {
        "name": "multi_field_compound_sort",
        "summary": "验证多字段组合排序 sort({age: 1, createdAt: -1}):先按年龄升序,同龄按创建时间降序。",
        "expected": expected,
        "actual": actual_list,
        "passed": actual_list == expected,
    }


def case_tutorial_col_likes_desc_with_projection():
    # Shuffle input first to verify sort restores descending likes order
    shuffled = [COL[2], COL[0], COL[1]]
    ordered = [{"title": d["title"]} for d in mongo_sort(shuffled, [("likes", -1)])]
    expected = [{"title": "PHP 教程"}, {"title": "Java 教程"}, {"title": "MongoDB 教程"}]
    return {
        "name": "tutorial_col_likes_desc_with_projection",
        "summary": "验证 col.find({}, {title: 1, _id: 0}).sort({likes: -1}) 按点赞数降序输出标题。",
        "expected": expected,
        "actual": ordered,
        "passed": ordered == expected,
    }


def case_sort_skip_limit_precedence_and_index_benefit():
    # Regardless of chaining order (.limit(2).skip(1).sort(...) vs .sort(...).skip(1).limit(2)),
    # MongoDB ALWAYS executes sort -> skip -> limit!
    def exec_query(docs, sort_spec, skip_n, limit_n):
        return mongo_sort(docs, sort_spec)[skip_n : skip_n + limit_n]

    res = [d["name"] for d in exec_query(USERS, [("age", -1)], skip_n=1, limit_n=2)]

    # Simulate indexed order scan vs in-memory blocking sort
    indexed_order = mongo_sort(USERS, [("age", -1)])  # pre-maintained B-tree index order
    index_top2 = [d["name"] for d in indexed_order[:2]]
    in_memory_comparisons_needed = False  # index already supplies sorted order

    actual = {
        "sort_skip_limit_names": res,
        "index_top2": index_top2,
        "blocking_sort_needed_with_index": in_memory_comparisons_needed,
    }
    expected = {
        "sort_skip_limit_names": ["Carol", "Alice"],
        "index_top2": ["David", "Carol"],
        "blocking_sort_needed_with_index": False,
    }
    return {
        "name": "sort_skip_limit_precedence_and_index_benefit",
        "summary": "验证 MongoDB 固定执行顺序 sort -> skip -> limit 以及有序索引消除内存阻塞排序的优势。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_single_field_asc_and_desc(),
        case_multi_field_compound_sort(),
        case_tutorial_col_likes_desc_with_projection(),
        case_sort_skip_limit_precedence_and_index_benefit(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/mongodb-sort-lab/explore-sort.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-sort.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:MongoDB

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

下载课程关联工程包:MongoDB

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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