MongoDB 自动增长
系统讲解 MongoDB 无内置 SQL AUTO_INCREMENT 的背景原因,以及如何借助 counters 集合与原子 findAndModify/findOneAndUpdate ($inc + returnDocument:'after') 实现并发安全的连续自增序列号生成器,并在离线脚本中完成多命名空间发号实测。
学完这一章,你能够
- 系统讲解 MongoDB 无内置 SQL AUTO_INCREMENT 的背景原因,以及如何借助 counters 集合与原子 findAndModify/findOneAndUpdate ($inc + returnDocument:'after') 实现并发安全的连续自增序列号生成器,并在离线脚本中完成多命名空间发号实测。
counters 集合发号模式与初始化
MongoDB 不提供关系型 SQL 数据库那样开箱即用的 `AUTO_INCREMENT` 主键列,默认以 12 字节 `ObjectId` 标识每条文档。但在订单号、工单编号或面向用户的简短数字 ID 场景下,业务仍常需要 `1, 2, 3, ...` 连续递增的整数 `_id`;对此可通过独立维护一张 `counters` 序列集合并在应用侧以原子递增命令编程实现。
以需要连续整数主键的 `products` 集合为例:先建立 `counters` 集合并插入一条以序列名 `"productid"` 为主键的初始计数器文档 `{_id: "productid", sequence_value: 0}`(现代命令推荐 `db.counters.insertOne(...)`),其中 `sequence_value` 负责持久化记录当前已分配到的最大序号。
封装原子递增函数并应用于文档写入
随后封装发号函数 `getNextSequenceValue(sequenceName)`:在服务端对 `counters` 集合执行单文档原子递增 `findAndModify({query: {_id: sequenceName}, update: {$inc: {sequence_value: 1}}, new: true})`——现代驱动与 `mongosh` 推荐写法为 `db.counters.findOneAndUpdate({_id: sequenceName}, {$inc: {sequence_value: 1}}, {returnDocument: "after", upsert: true})`。由于 `$inc` 与读取新值在单文档锁内原子完成,即使多客户端高并发同时请求也不会发出重复序号。
写入业务商品时直接将 `getNextSequenceValue("productid")` 的返回值赋给 `_id` 字段,连续插入 `Apple iPhone` 与 `Samsung S3` 后查询 `db.products.find()`,即可观察到 `_id` 按 `1`、`2` 严格递增。需要提示的是:生产应用应将发号逻辑放在应用服务层调用驱动 API(而非依赖已废弃的服务端存储 JavaScript 函数),且在超高吞吐分片场景下建议改用批量预取号段或 ObjectId 以免单一计数器文档成为写热点。离线序列生成器已验证 `productid` 连续分配 `1, 2, 3` 及独立 `orderid` 命名空间 `upsert` 发号。
离线验证 counters 集合原子 $inc 自增序列发号与多序列命名空间隔离
展开查看收起
"""Offline MongoDB atomic counters collection auto-increment sequence verifier."""
import json
VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"
class SequenceStore:
def __init__(self):
self.counters = {}
self.products = []
def init_counter(self, seq_name, start=0):
self.counters[seq_name] = {"_id": seq_name, "sequence_value": start}
def get_next_sequence_value(self, seq_name, upsert=True):
if seq_name not in self.counters:
if not upsert:
raise KeyError(f"Counter {seq_name} not found")
self.counters[seq_name] = {"_id": seq_name, "sequence_value": 0}
# Atomic $inc: {sequence_value: 1} with returnDocument: "after" (new: true)
self.counters[seq_name]["sequence_value"] += 1
return self.counters[seq_name]["sequence_value"]
def insert_product(self, product_name, category):
next_id = self.get_next_sequence_value("productid")
doc = {"_id": next_id, "product_name": product_name, "category": category}
self.products.append(doc)
return doc
def main():
store = SequenceStore()
store.init_counter("productid", start=0)
# Case 1: Initialize counters doc and generate sequential product IDs 1, 2, 3
p1 = store.insert_product("Apple iPhone", "mobiles")
p2 = store.insert_product("Samsung S3", "mobiles")
p3 = store.insert_product("Pixel 9", "mobiles")
c1_actual = {
"products": [p1, p2, p3],
"counter_doc": dict(store.counters["productid"]),
}
c1_expected = {
"products": [
{"_id": 1, "product_name": "Apple iPhone", "category": "mobiles"},
{"_id": 2, "product_name": "Samsung S3", "category": "mobiles"},
{"_id": 3, "product_name": "Pixel 9", "category": "mobiles"},
],
"counter_doc": {"_id": "productid", "sequence_value": 3},
}
# Case 2: Independent sequence namespaces & upsert initialization
order_id_1 = store.get_next_sequence_value("orderid", upsert=True)
order_id_2 = store.get_next_sequence_value("orderid", upsert=True)
product_id_4 = store.get_next_sequence_value("productid")
c2_actual = {
"order_ids": [order_id_1, order_id_2],
"next_product_id": product_id_4,
"counter_keys": sorted(store.counters.keys()),
}
c2_expected = {
"order_ids": [1, 2],
"next_product_id": 4,
"counter_keys": ["orderid", "productid"],
}
cases = [
{
"name": "counters_atomic_increment_products",
"summary": "Verify counters collection + atomic $inc (new: true) assigns sequential _id 1, 2, 3 to products.",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "independent_named_sequences_upsert",
"summary": "Verify separate named counters ('orderid' vs 'productid') increment independently with upsert support.",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
默认情况下这两个方法返回更新前的旧文档;只有指定 new: true / returnDocument: 'after' 才会返回原子 $inc 递增后的最新 sequence_value,使首次发号从 1 而非 0 开始。