MongoDB 创建集合
详解 MongoDB db.createCollection(name, options) 的全部 8 项核心配置参数(capped/size/max、$jsonSchema 验证器、WiredTiger 存储引擎与 collation),以及显式建集合与隐式写文档建集合的差异。
学完这一章,你能够
- 详解 MongoDB db.createCollection(name, options) 的全部 8 项核心配置参数(capped/size/max、$jsonSchema 验证器、WiredTiger 存储引擎与 collation),以及显式建集合与隐式写文档建集合的差异。
createCollection() 语法与核心配置选项
在 MongoDB 中可通过 `db.createCollection(name, options)` 显式创建集合:`name` 为集合名称,`options` 为可选配置对象,用于定义固定集合上限、文档模式校验规则、WiredTiger 块压缩参数与默认排序规则等(见下方完整参数对照表)。需注意,当集合启用固定大小(`capped: true`)并同时配置了字节数 `size` 与最大文档数 `max` 时,写入文档会先检查 `size` 字节上限,再检查 `max` 文档数上限,超出任一阈值即按 FIFO 淘汰最旧记录。
复合配置实例与验证器、存储引擎及排序规则
在工程实践中可将多个选项组合使用,例如创建 `myComplexCollection`:设定 `capped: true`、最大 `10MB`(`10485760` 字节)且最多容纳 `5000` 条文档;通过 `validator: { $jsonSchema: { ... } }` 强制文档包含字符串 `name` 与符合 `^.+@.+$` 正则格式的 `email`;设置 `validationLevel: "strict"` 与 `validationAction: "error"` 严格拦截违规写入;通过 `storageEngine.wiredTiger.configString` 指定 `block_compressor=zstd` 块压缩器;并以 `collation: { locale: "en", strength: 2 }` 设定默认不区分大小写的英语排序规则。
基础建集合、隐式创建与常见配置模板
日常最简创建方式为切换数据库后执行 `db.createCollection("demo")`(返回 `{ "ok": 1 }`),随后以 `show collections` 或 `show tables` 查验集合列表(注意历史版本曾额外显示 `system.indexes`,现代 WiredTiger 已不再列出该系统集合)。如果不需特殊配置,MongoDB 支持完全隐式建集合——直接向新集合 `insertOne()`(历史示例为 `insert()`)即可自动创建集合。常见的显式模板包括:仅设 `5MB` 与 `5000` 条上限或 `1MB` 字节上限的固定日志集合,以及要求 `name` 为必填字符串、`age` 为非负整数(`minimum: 0`)的 `$jsonSchema` 校验集合。
db.createCollection() options 核心参数说明
| 参数名 | 类型 | 功能描述 | 示例值 |
|---|---|---|---|
| capped | 布尔值 | 是否创建固定大小循环集合;设为 true 时必须同时指定 size。 | true |
| size | 数值 | 固定集合最大容量(单位:字节),仅在 capped 为 true 时生效。 | 10485760 (10MB) |
| max | 数值 | 固定集合允许存放的最大文档数量,仅在 capped 为 true 时生效。 | 5000 |
| validator | 对象 | 声明文档校验规则的表达式对象,推荐使用 $jsonSchema。 | { $jsonSchema: { ... } } |
| validationLevel | 字符串 | 校验严格度:"strict"(默认,插改全校验)、"moderate"(仅校验合规存量更新与新文档)或 "off"(关闭)。 | "strict" |
| validationAction | 字符串 | 校验失败时的动作:"error"(默认,拒绝写入并报错)或 "warn"(允许写入并记录日志告警)。 | "error" |
| storageEngine | 对象 | 为集合指定存储引擎级参数,例如 WiredTiger 的块压缩算法配置。 | { wiredTiger: { ... } } |
| collation | 对象 | 配置集合默认语言环境与比较强度(如大小写、重音敏感度)。 | { locale: "en", strength: 2 } |
运行隐式/显式建集合、固定集合 size/max 淘汰、$jsonSchema 严格/告警校验及 collation 验证
"""Offline MongoDB createCollection options, capped eviction, $jsonSchema & collation verifier (Ch13)."""
import json
import re
VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"
def validate_json_schema(doc: dict, schema: dict) -> tuple[bool, str]:
if schema.get("bsonType") == "object" and not isinstance(doc, dict):
return False, "not_object"
for req in schema.get("required", []):
if req not in doc:
return False, f"missing_{req}"
for field, rule in schema.get("properties", {}).items():
if field not in doc:
continue
val = doc[field]
bt = rule.get("bsonType")
if bt == "string" and not isinstance(val, str):
return False, f"{field}_not_string"
if bt == "int" and (isinstance(val, bool) or not isinstance(val, int)):
return False, f"{field}_not_int"
if "pattern" in rule and isinstance(val, str) and not re.search(rule["pattern"], val):
return False, f"{field}_pattern_mismatch"
if "minimum" in rule and isinstance(val, (int, float)) and val < rule["minimum"]:
return False, f"{field}_below_minimum"
return True, "ok"
class OfflineCollection:
def __init__(self, name: str, options: dict | None = None):
self.name = name
self.options = options or {}
self.docs = []
self.warnings = []
self.cur_bytes = 0
def insert_one(self, doc: dict):
level = self.options.get("validationLevel", "strict")
action = self.options.get("validationAction", "error")
schema = (self.options.get("validator") or {}).get("$jsonSchema")
if schema and level == "strict":
ok, reason = validate_json_schema(doc, schema)
if not ok:
if action == "error":
return {"ok": False, "error": reason}
self.warnings.append(reason)
rec = dict(doc)
sz = len(json.dumps(rec, ensure_ascii=False).encode("utf-8"))
self.docs.append((rec, sz))
self.cur_bytes += sz
if self.options.get("capped"):
max_size = self.options.get("size")
max_docs = self.options.get("max")
# MongoDB checks size first, then max
while (max_size is not None and self.cur_bytes > max_size) or (
max_docs is not None and len(self.docs) > max_docs
):
_, old_sz = self.docs.pop(0)
self.cur_bytes -= old_sz
return {"ok": True}
def case_basic_and_implicit_collection_creation():
collections = {}
collections["demo"] = OfflineCollection("demo")
explicit_ok = "demo" in collections
# Implicit creation on first insert
collections.setdefault("mycol2", OfflineCollection("mycol2")).insert_one({"name": "蓝色天空网"})
actual = {
"explicit_created": explicit_ok,
"collections": sorted(collections.keys()),
"mycol2_count": len(collections["mycol2"].docs),
}
expected = {
"explicit_created": True,
"collections": ["demo", "mycol2"],
"mycol2_count": 1,
}
return {
"name": "basic_and_implicit_collection_creation",
"summary": "验证 db.createCollection() 显式建集合与首次插入文档时隐式自动建集合。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_capped_collection_size_and_max_eviction():
col = OfflineCollection("myCappedCollection", {"capped": True, "size": 100, "max": 3})
for i in range(1, 6):
col.insert_one({"id": i, "tag": f"log-{i}"})
remaining_ids = [d["id"] for d, _ in col.docs]
actual = {
"remaining_ids": remaining_ids,
"within_size": col.cur_bytes <= 100,
"within_max": len(col.docs) <= 3,
}
expected = {"remaining_ids": [3, 4, 5], "within_size": True, "within_max": True}
return {
"name": "capped_collection_size_and_max_eviction",
"summary": "验证固定集合同时受 size(字节)与 max(文档数)约束时先检查 size 再检查 max 的 FIFO 淘汰。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_jsonschema_validator_strict_moderate_off():
schema = {
"$jsonSchema": {
"bsonType": "object",
"required": ["name", "age"],
"properties": {
"name": {"bsonType": "string"},
"age": {"bsonType": "int", "minimum": 0},
},
}
}
strict_err = OfflineCollection("c1", {"validator": schema, "validationLevel": "strict", "validationAction": "error"})
strict_warn = OfflineCollection("c2", {"validator": schema, "validationLevel": "strict", "validationAction": "warn"})
off_col = OfflineCollection("c3", {"validator": schema, "validationLevel": "off"})
bad_doc = {"name": "Bob", "age": -3}
good_doc = {"name": "Alice", "age": 28}
r_bad_err = strict_err.insert_one(bad_doc)
r_good_err = strict_err.insert_one(good_doc)
r_bad_warn = strict_warn.insert_one(bad_doc)
r_bad_off = off_col.insert_one(bad_doc)
actual = {
"strict_error_rejects_bad": r_bad_err,
"strict_error_accepts_good": r_good_err["ok"],
"strict_warn_allows_and_logs": [r_bad_warn["ok"], strict_warn.warnings],
"off_allows_bad": r_bad_off["ok"],
}
expected = {
"strict_error_rejects_bad": {"ok": False, "error": "age_below_minimum"},
"strict_error_accepts_good": True,
"strict_warn_allows_and_logs": [True, ["age_below_minimum"]],
"off_allows_bad": True,
}
return {
"name": "jsonschema_validator_strict_moderate_off",
"summary": "验证 $jsonSchema 必填与类型/最小值校验,以及 validationLevel(strict/off) 与 validationAction(error/warn)。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_complex_collection_options_storage_collation():
opts = {
"capped": True,
"size": 10485760,
"max": 5000,
"validator": {
"$jsonSchema": {
"bsonType": "object",
"required": ["name", "email"],
"properties": {
"name": {"bsonType": "string"},
"email": {"bsonType": "string", "pattern": r"^.+@.+$"},
},
}
},
"validationLevel": "strict",
"validationAction": "error",
"storageEngine": {"wiredTiger": {"configString": "block_compressor=zstd"}},
"collation": {"locale": "en", "strength": 2},
}
col = OfflineCollection("myComplexCollection", opts)
r1 = col.insert_one({"name": "Alice", "email": "alice@example.com"})
r2 = col.insert_one({"name": "Bob", "email": "invalid-email"})
# strength=2 compares base characters & accents, ignoring case in en locale
ci_equal = "Cafe".casefold() == "cafe".casefold()
actual = {
"valid_email_inserted": r1["ok"],
"bad_email_error": r2["error"],
"compressor": opts["storageEngine"]["wiredTiger"]["configString"],
"collation_strength2_case_insensitive": ci_equal,
}
expected = {
"valid_email_inserted": True,
"bad_email_error": "email_pattern_mismatch",
"compressor": "block_compressor=zstd",
"collation_strength2_case_insensitive": True,
}
return {
"name": "complex_collection_options_storage_collation",
"summary": "验证综合建集合配置:capped、email 正则验证器、WiredTiger zstd 压缩及 en strength:2 排序规则。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_collection_options_table_contract():
option_names = [
"capped",
"size",
"max",
"validator",
"validationLevel",
"validationAction",
"storageEngine",
"collation",
]
actual = {"option_count": len(option_names), "defaults": {"validationLevel": "strict", "validationAction": "error"}}
expected = {"option_count": 8, "defaults": {"validationLevel": "strict", "validationAction": "error"}}
return {
"name": "collection_options_table_contract",
"summary": "核对 createCollection 全部 8 个选项参数清单与默认校验行为。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_basic_and_implicit_collection_creation(),
case_capped_collection_size_and_max_eviction(),
case_jsonschema_validator_strict_moderate_off(),
case_complex_collection_options_storage_collation(),
case_collection_options_table_contract(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 验证显式与隐式建集合、capped FIFO 淘汰顺序、$jsonSchema 拦截负年龄与告警模式及 zstd/strength:2 规则。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:ca5330cdcb9b5085f1d551dfff6ee7f84d94c7aee0a20274fe33806e81d4dd5b
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:0fb4eb0545a35ca35dfedfca450cee93185f76a2cff23e8f73c5e12557fe0bee
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
若希望对已有历史脏数据的集合上线 `$jsonSchema` 校验,但又不想阻断现有业务写入,应如何搭配 `validationLevel` 与 `validationAction`?
展开参考解答
上线观察期可先设 `validationAction: "warn"` 仅记录日志而不阻断写入;若仅约束新写入和原本合规的文档,则配合 `validationLevel: "moderate"`。