蓝色天空网mbsky.com · 知识 · 实践 · 创造MongoDB · 本地阅读预览
教程 / 数据库 / MongoDB

Node.js MongoDB

系统梳理 Node.js 官方 mongodb 驱动安装、MongoClient 连接 URI、async/await 全套 CRUD、排序分页、$lookup 左外连接、集合删除与现代原生 Promise 用法,并在离线脚本中验证全部数据操作契约。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

Node.js 驱动安装、MongoClient 连接与库/集合创建

MongoDB 是以 C++ 编写的文档导向型数据库,在 Node.js 中可通过官方驱动包 `mongodb`(使用 `npm install mongodb` 或镜像加速工具安装)建立异步连接。引入 `{ MongoClient }` 后调用 `await client.connect()` 建立连接,并在 `finally` 块中执行 `await client.close()` 释放连接池资源。

连接配置围绕三大要素:`MongoClient` 客户端类、标准连接字符串 `uri`(格式 `mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]`)以及连接选项。需要特别说明的是,旧版教程常见的 `useNewUrlParser` 与 `useUnifiedTopology` 选项自 Node.js 驱动 v4.0 起已默认生效并标记为废弃,v6+ 驱动中直接省略即可。

通过 `const database = client.db('demo_app')` 即可指向目标数据库;若数据库尚不存在,MongoDB 会在首次创建集合或写入文档时自动建立。集合既可通过 `await database.createCollection('exampleCollection')` 显式创建,也可在调用 `database.collection('exampleCollection').insertOne(doc)` 写入数据时按需自动生成。

async/await 文档增删改查(CRUD)

与关系型数据库必须先建表不同,MongoDB 支持免预建结构直接写入。单条写入调用 `await collection.insertOne(doc)` 并通过 `result.insertedId` 获取生成的 ObjectId(可在客户端 `show dbs` / `show collections` / `find()` 复核);批量写入调用 `await collection.insertMany(docs)`,返回对象包含 `insertedCount` 与按数组下标映射的 `insertedIds` 字典。

查询文档使用 `collection.find(query, options)`,传入空对象 `{}` 返回全集合文档,传入 `{ name: 'Alice' }` 按条件筛选;通过 `options.projection`(如 `{ _id: 0, name: 1, age: 1, address: 1 }`)精确控制返回字段,并调用 `await cursor.toArray()` 将游标转为结果数组。

修改文档使用 `updateOne(filter, { $set: ... })` 更新首条匹配记录或 `updateMany(filter, { $set: ... })` 批量更新全部匹配记录,返回对象中的 `matchedCount` 与 `modifiedCount` 分别反映命中数与实际变更数。删除文档对应使用 `deleteOne(filter)` 与 `deleteMany(filter)`,返回 `deletedCount` 指示已删条数(离线验证脚本实测在 4 条文档上依次完成单/多条更新与删除后仅剩 Charlie 1 条记录)。

排序分页、$lookup 左连接、drop 与现代 Promise 写法

游标链式方法支持灵活的排序与分页:`.sort({ age: 1 })` 按升序排列、`.sort({ age: -1 })` 按降序排列;`.limit(n)` 限制最大返回条数(注意源示例标题写 2 条而代码中写 `limit(3)`,应以实际传入参数为准);`.skip(k)` 跳过前 `k` 条文档,配合 `.limit()` 即可组合出标准分页查询。

跨集合关联可通过聚合管道的 `$lookup` 阶段实现左外连接:在 `orders` 集合上指定 `from: 'products'`、`localField: 'product_id'`、`foreignField: '_id'`、`as: 'productDetails'`,即可把匹配的 `products` 文档数组合并进每笔订单(离线验证返回 Product A/B/C 及总金额 100/70/400)。销毁整张集合调用 `await database.collection('test').drop()`(返回布尔值表示是否删除成功)。

在异步编排方面,ES6 `Promise` 与 `async/await` 能够清晰串联增、查、改、删四步连续任务。需要特别纠正的是:早期教程中用 `new Promise((resolve, reject) => client.connect(cb))` 或在 `insertOne`/`find().toArray` 中传回调函数的写法属于 Node.js 驱动 v3/v4 旧风格;自官方驱动 v5.0 起已彻底移除回调接口,所有驱动方法均原生返回 Promise,且构造 ObjectId 必须使用 `new ObjectId(id)`。离线脚本已完整验证连接 URI、全套 CRUD、排序分页、`$lookup` 与四步 Promise 生命周期。

离线验证 Node.js MongoClient URI、async/await CRUD、排序分页与 $lookup 左连接

python · 阅读源码
"""Offline Node.js MongoDB Driver async/await CRUD, pagination & $lookup verifier."""
import json
from urllib.parse import urlparse

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


class MockNodeCollection:
    def __init__(self, name):
        self.name = name
        self.docs = []
        self._seq = 1

    def insert_one(self, doc):
        row = dict(doc)
        row.setdefault("_id", f"6678e1d1f9503dc2e0e2a{self._seq:03x}")
        self._seq += 1
        self.docs.append(row)
        return {"insertedId": row["_id"]}

    def insert_many(self, docs):
        ids = {}
        for idx, d in enumerate(docs):
            res = self.insert_one(d)
            ids[idx] = res["insertedId"]
        return {"insertedCount": len(docs), "insertedIds": ids}

    def find(self, flt=None, projection=None, sort=None, skip=0, limit=None):
        flt = flt or {}
        rows = [dict(d) for d in self.docs if all(d.get(k) == v for k, v in flt.items())]
        if sort:
            for k, direction in reversed(list(sort.items())):
                rows.sort(key=lambda x, f=k: x.get(f), reverse=(direction == -1))
        if skip:
            rows = rows[skip:]
        if limit is not None:
            rows = rows[:limit]
        if projection:
            include_id = projection.get("_id", 1) != 0
            projected = []
            for r in rows:
                item = {}
                if include_id and "_id" in r:
                    item["_id"] = r["_id"]
                for k, v in projection.items():
                    if k != "_id" and v == 1 and k in r:
                        item[k] = r[k]
                projected.append(item)
            rows = projected
        return rows

    def update_one(self, flt, upd):
        for d in self.docs:
            if all(d.get(k) == v for k, v in flt.items()):
                d.update(upd.get("$set", {}))
                return {"matchedCount": 1, "modifiedCount": 1}
        return {"matchedCount": 0, "modifiedCount": 0}

    def update_many(self, flt, upd):
        matched = 0
        for d in self.docs:
            if all(d.get(k) == v for k, v in flt.items()):
                d.update(upd.get("$set", {}))
                matched += 1
        return {"matchedCount": matched, "modifiedCount": matched}

    def delete_one(self, flt):
        for idx, d in enumerate(self.docs):
            if all(d.get(k) == v for k, v in flt.items()):
                self.docs.pop(idx)
                return {"deletedCount": 1}
        return {"deletedCount": 0}

    def delete_many(self, flt):
        before = len(self.docs)
        self.docs = [d for d in self.docs if not all(d.get(k) == v for k, v in flt.items())]
        return {"deletedCount": before - len(self.docs)}


def lookup_join(left_docs, right_docs, local_field, foreign_field, as_field):
    right_index = {}
    for rd in right_docs:
        right_index.setdefault(rd[foreign_field], []).append(dict(rd))
    out = []
    for ld in left_docs:
        merged = dict(ld)
        merged[as_field] = list(right_index.get(ld.get(local_field), []))
        out.append(merged)
    return out


def main():
    # Case 1: URI parsing & database/collection creation
    uri = "mongodb://localhost:27017/demo_app?retryWrites=true"
    parsed = urlparse(uri)
    col = MockNodeCollection("exampleCollection")
    r_one = col.insert_one({"name": "Example", "type": "Test"})
    c1_actual = {
        "scheme": parsed.scheme,
        "host": parsed.hostname,
        "port": parsed.port,
        "db": parsed.path.lstrip("/"),
        "inserted_id_len": len(r_one["insertedId"]),
        "driver_v4_plus_deprecated_opts": ["useNewUrlParser", "useUnifiedTopology"],
    }
    c1_expected = {
        "scheme": "mongodb",
        "host": "localhost",
        "port": 27017,
        "db": "demo_app",
        "inserted_id_len": 24,
        "driver_v4_plus_deprecated_opts": ["useNewUrlParser", "useUnifiedTopology"],
    }

    # Case 2: insertMany, find with projection & filter, updateOne, updateMany, deleteOne, deleteMany
    crud = MockNodeCollection("users")
    ins = crud.insert_many([
        {"name": "Alice", "age": 25, "address": "Wonderland"},
        {"name": "Bob", "age": 30, "address": "Builderland"},
        {"name": "Alice", "age": 28, "address": "Old Wonderland"},
        {"name": "Charlie", "age": 35, "address": "Chocolate Factory"},
    ])
    found_alice = crud.find({"name": "Alice"}, projection={"_id": 0, "name": 1, "age": 1})
    u1 = crud.update_one({"name": "Alice"}, {"$set": {"age": 26, "address": "New Wonderland"}})
    um = crud.update_many({"name": "Alice"}, {"$set": {"address": "Updated Wonderland"}})
    d1 = crud.delete_one({"name": "Bob"})
    dm = crud.delete_many({"name": "Alice"})
    remaining_names = [d["name"] for d in crud.find({}, projection={"_id": 0, "name": 1})]
    c2_actual = {
        "inserted_count": ins["insertedCount"],
        "alice_initial_ages": [d["age"] for d in found_alice],
        "update_one_modified": u1["modifiedCount"],
        "update_many_modified": um["modifiedCount"],
        "delete_one_count": d1["deletedCount"],
        "delete_many_count": dm["deletedCount"],
        "remaining_names": remaining_names,
    }
    c2_expected = {
        "inserted_count": 4,
        "alice_initial_ages": [25, 28],
        "update_one_modified": 1,
        "update_many_modified": 2,
        "delete_one_count": 1,
        "delete_many_count": 2,
        "remaining_names": ["Charlie"],
    }

    # Case 3: sort({age: 1 / -1}), limit(3), skip(2)
    page_col = MockNodeCollection("people")
    page_col.insert_many([
        {"name": "Alice", "age": 25},
        {"name": "Bob", "age": 30},
        {"name": "Charlie", "age": 35},
        {"name": "Dave", "age": 20},
        {"name": "Eve", "age": 22},
    ])
    asc_names = [d["name"] for d in page_col.find(sort={"age": 1})]
    desc_names = [d["name"] for d in page_col.find(sort={"age": -1})]
    lim3 = [d["name"] for d in page_col.find(limit=3)]
    skip2 = [d["name"] for d in page_col.find(skip=2)]
    c3_actual = {"asc": asc_names, "desc": desc_names, "limit3": lim3, "skip2": skip2}
    c3_expected = {
        "asc": ["Dave", "Eve", "Alice", "Bob", "Charlie"],
        "desc": ["Charlie", "Bob", "Alice", "Eve", "Dave"],
        "limit3": ["Alice", "Bob", "Charlie"],
        "skip2": ["Charlie", "Dave", "Eve"],
    }

    # Case 4: $lookup left outer join (orders -> products), collection drop & Promise CRUD cycle
    orders = [
        {"_id": 1, "product_id": 101, "quantity": 2},
        {"_id": 2, "product_id": 102, "quantity": 1},
        {"_id": 3, "product_id": 103, "quantity": 4},
    ]
    products = [
        {"_id": 101, "name": "Product A", "price": 50},
        {"_id": 102, "name": "Product B", "price": 70},
        {"_id": 103, "name": "Product C", "price": 100},
        {"_id": 104, "name": "Product D", "price": 120},
    ]
    joined = lookup_join(orders, products, "product_id", "_id", "productDetails")
    # Simulate sequential Promise CRUD lifecycle: insert -> find -> update -> delete -> drop
    lifecycle = MockNodeCollection("documents")
    lid = lifecycle.insert_one({"name": "Document 1"})["insertedId"]
    after_ins = [d["name"] for d in lifecycle.find()]
    lifecycle.update_one({"_id": lid}, {"$set": {"name": "Updated Document 1"}})
    after_upd = [d["name"] for d in lifecycle.find()]
    lifecycle.delete_one({"_id": lid})
    after_del = lifecycle.find()
    c4_actual = {
        "lookup_product_names": [row["productDetails"][0]["name"] for row in joined],
        "lookup_total_order_values": [row["quantity"] * row["productDetails"][0]["price"] for row in joined],
        "lifecycle": [after_ins, after_upd, after_del],
    }
    c4_expected = {
        "lookup_product_names": ["Product A", "Product B", "Product C"],
        "lookup_total_order_values": [100, 70, 400],
        "lifecycle": [["Document 1"], ["Updated Document 1"], []],
    }

    cases = [
        {
            "name": "node_connect_uri_and_options",
            "summary": "Verify Node.js MongoClient URI parsing, insertOne ID generation, and v4+ deprecated options note.",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "node_crud_insert_find_update_delete",
            "summary": "Verify insertMany, find with projection, updateOne/updateMany, and deleteOne/deleteMany.",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
        {
            "name": "node_sort_limit_skip_pagination",
            "summary": "Verify cursor sort ascending/descending, limit(3), and skip(2) pagination behavior.",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_expected,
        },
        {
            "name": "node_lookup_drop_and_promise_chain",
            "summary": "Verify $lookup left outer join between orders and products plus sequential Promise CRUD lifecycle.",
            "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()
预期结果 · 待实际运行核验
  • 在离线脚本中验证 URI 解析、insertMany/find/updateOne/updateMany/deleteOne/deleteMany、sort/limit/skip 分页、orders-products $lookup 关联及连续 CRUD 生命周期全部通过。
离线验证 Node.js MongoClient URI、async/await CRUD、排序分页与 $lookup 左连接

所需环境:Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。

当前源码 SHA256:1be523083be8a237e70968f99e367415ff25a772403ad53f8d706302a200ab3a

下载本站示例源码

本地运行

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

下载Node.js MongoDB实验

所需环境:Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。

ZIP SHA256:d2eaba24b96d1c7ad344c30506f659d91a240fdfe744339c7d71c111f84a9461

常见错误与边界

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

练习与解答

在 Node.js MongoDB 官方驱动 v5/v6 中,为什么不再需要手写 new Promise 包装 client.connect(callback)?

展开参考解答

因为 v5+ 驱动已经彻底移除回调函数签名,client.connect()、insertOne()、toArray() 等所有异步方法均原生返回标准 Promise,直接配合 async/await 或 .then()/.catch() 即可使用。

规范与官方依据