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

离线验证 Java Driver 连接认证契约、集合读写游标与 updateMany/deleteOne/deleteMany

PYTHONWindows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。explore-java.py
explore-java.py154 行
"""Offline MongoDB Java Driver connection, authentication, and CRUD contract verifier."""
import json
from urllib.parse import urlparse

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


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

    def insert_many(self, documents):
        for d in documents:
            row = dict(d)
            row.setdefault("_id", f"56e65fb1fd57a86304fe26{self._seq:02x}")
            self._seq += 1
            self.docs.append(row)
        return len(documents)

    def find(self):
        return [dict(d) for d in self.docs]

    def update_many(self, field, target_val, set_fields):
        modified = 0
        for d in self.docs:
            if d.get(field) == target_val:
                d.update(set_fields)
                modified += 1
        return modified

    def delete_one(self, field, target_val):
        for idx, d in enumerate(self.docs):
            if d.get(field) == target_val:
                self.docs.pop(idx)
                return 1
        return 0

    def delete_many(self, field, target_val):
        before = len(self.docs)
        self.docs = [d for d in self.docs if d.get(field) != target_val]
        return before - len(self.docs)


class MockJavaMongoDatabase:
    def __init__(self, name):
        self.name = name
        self.collections = {}

    def create_collection(self, col_name):
        self.collections.setdefault(col_name, MockJavaMongoCollection(col_name))
        return col_name

    def get_collection(self, col_name):
        return self.collections.setdefault(col_name, MockJavaMongoCollection(col_name))


def main():
    # Case 1: Connection URI & SCRAM credential parsing (legacy 3.x vs modern 4.x/5.x MongoClients)
    uri = "mongodb://appuser:secret@localhost:27017/databaseName?authSource=databaseName&authMechanism=SCRAM-SHA-256"
    parsed = urlparse(uri)
    c1_actual = {
        "scheme": parsed.scheme,
        "host": parsed.hostname,
        "port": parsed.port,
        "username": parsed.username,
        "database": parsed.path.lstrip("/"),
        "scram_credential_tuple": ["username", "databaseName", "SCRAM-SHA-1/256"],
    }
    c1_expected = {
        "scheme": "mongodb",
        "host": "localhost",
        "port": 27017,
        "username": "appuser",
        "database": "databaseName",
        "scram_credential_tuple": ["username", "databaseName", "SCRAM-SHA-1/256"],
    }

    # Case 2: createCollection, getCollection, insertMany, find cursor iteration
    db = MockJavaMongoDatabase("mycol")
    db.create_collection("test")
    col = db.get_collection("test")
    inserted = col.insert_many([
        {"title": "MongoDB", "description": "database", "likes": 100, "by": "Fly"},
        {"title": "MongoDB Guide", "description": "database", "likes": 100, "by": "Alex"},
    ])
    found_titles = [d["title"] for d in col.find()]
    c2_actual = {
        "db_name": db.name,
        "collection_name": col.name,
        "inserted_count": inserted,
        "cursor_titles": found_titles,
    }
    c2_expected = {
        "db_name": "mycol",
        "collection_name": "test",
        "inserted_count": 2,
        "cursor_titles": ["MongoDB", "MongoDB Guide"],
    }

    # Case 3: updateMany(Filters.eq("likes", 100), $set likes=200), deleteOne & deleteMany
    modified = col.update_many("likes", 100, {"likes": 200})
    likes_after_update = [d["likes"] for d in col.find()]
    del_one = col.delete_one("likes", 200)
    remaining_after_one = len(col.find())
    del_many = col.delete_many("likes", 200)
    remaining_after_many = len(col.find())
    c3_actual = {
        "modified_count": modified,
        "likes_after_update": likes_after_update,
        "deleted_one": del_one,
        "remaining_after_one": remaining_after_one,
        "deleted_many": del_many,
        "remaining_after_many": remaining_after_many,
    }
    c3_expected = {
        "modified_count": 2,
        "likes_after_update": [200, 200],
        "deleted_one": 1,
        "remaining_after_one": 1,
        "deleted_many": 1,
        "remaining_after_many": 0,
    }

    cases = [
        {
            "name": "java_driver_connection_and_auth",
            "summary": "Verify Java driver connection URI, host/port, database selection, and SCRAM credential parameters.",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "java_collection_insert_and_cursor",
            "summary": "Verify createCollection, getCollection, insertMany(List<Document>), and MongoCursor iteration.",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
        {
            "name": "java_update_many_and_delete_ops",
            "summary": "Verify updateMany with Filters.eq/$set followed by deleteOne and deleteMany semantics.",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_expected,
        },
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

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

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-java.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:MongoDB

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

下载课程关联工程包:MongoDB

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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