文档、BSON 与种子数据
MongoDB 在运行,可 bookstore 还是空的。这一章先弄清文档里每个值到底是什么类型,再把后面各章共用的标准数据导进去,让每章都能从同一状态出发。
从 JSON 到 BSON
mongosh 里的文档像 JavaScript 对象,传输和存储用的是 BSON。它保留 JSON 的键值结构,又补上数据库需要的类型:Int32、Int64、Double、Decimal128 四种数字,日期,二进制,ObjectId。数字类型不同,校验会区分,比较按数值。
一张订单里有字符串(_id、status)、数组(items,元素是嵌套文档)、整数(unitPrice、quantity、total)和日期(createdAt)。createdAt 是 BSON 日期,不是长得像日期的字符串。

字段是什么类型,让服务器自己说。先进入 mongosh(提示符里的 test 是默认数据库):
docker exec -it paperboat-mongo mongosh下面的 javascript 命令都在这个会话里执行。先写一份示范文档,用 $type 看类型:
use bookstore
db.probe.insertOne({ plain: 89, explicit: NumberInt(89), dbl: Double(89), frac: 89.5 })
db.probe.aggregate([{ $project: { _id: 0, plain: { $type: "$plain" }, explicit: { $type: "$explicit" },
dbl: { $type: "$dbl" }, frac: { $type: "$frac" } } }])[ { plain: 'int', explicit: 'int', dbl: 'double', frac: 'double' } ]容易误会的是:mongosh 2.x 会把 32 位范围内的整数字面量自动存成 int,所以 89 和 NumberInt(89) 结果一样;而 Double(89) 显示出来也是 89,肉眼分不出,只有 $type 能揭穿。种子脚本统一写 NumberInt,把意图写明,不靠 shell 的自动判断。
把整数换成 42,看看哪几张纸页读出的数字一样,再点开一张订单的明细。
第 1 题 · 单选题
_id 与 ObjectId
每个文档都有 _id,在集合里必须唯一,写入后不能修改。没写时,会替你生成一个 ObjectId:
const r = db.probe.insertOne({ n: 1 })
r.insertedId.toString()
r.insertedId.getTimestamp()6afef4e0a27dd628d7e10523
ISODate('2026-11-19T13:08:48.000Z')你的 ID 和时间不会相同。ObjectId 是 12 个字节:4 字节秒级时间戳,5 字节随机值,3 字节递增计数器,所以大致按创建时间排序,不同机器几乎不会重复。重复的 _id 会得到 E11000 duplicate key error,改 _id 会被拒绝。试完 db.probe.drop()。

本书的实体用可读字符串,如 book-mongodb:命令能原样复制,结果不受随机值影响;代价是要自己保证唯一。没有天然业务主键时,ObjectId 往往更省心。单个文档最大 16 MB,第 7 章会量。
库和集合第一次写入时才出现
use bookstore 只是让 db 指向它,不会创建它。库和集合都在第一次写入时才出现:use demo 之后,数据库列表里没有 demo;执行一次 db.probe.insertOne({ x: 1 }),列表里才多出 'demo'。
seed.js:三段数据
标准数据由一个脚本生成。把下面三段按顺序放进同一个文件 paperboat/scripts/seed.js(已挂载到容器的 /scripts)。第一段删旧集合,建集合和订单校验器:
for (const name of ["books", "customers", "orders"]) {
db.getCollection(name).drop();
}
db.createCollection("books");
db.createCollection("customers");
db.createCollection("orders", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["customerId", "status", "items", "total", "createdAt"],
properties: {
customerId: { bsonType: "string" },
status: { enum: ["pending", "paid", "shipped", "cancelled"] },
items: {
bsonType: "array",
minItems: 1,
items: {
bsonType: "object",
required: ["bookId", "title", "unitPrice", "quantity"],
properties: {
bookId: { bsonType: "string" },
title: { bsonType: "string" },
unitPrice: { bsonType: "int", minimum: 0 },
quantity: { bsonType: "int", minimum: 1 }
}
}
},
total: { bsonType: "int", minimum: 0 },
createdAt: { bsonType: "date" }
}
}
}
});校验器只管不能缺的:五个必填字段,status 只有四个合法值,明细至少一项,价格是非负整数,数量是正整数,createdAt 是日期。没列出的字段(比如以后的配送信息)照样允许。
第二段是书和顾客。八本书有意拉开差异:价格并列、库存只剩 1 和 3、一本未上架的草稿;陈帆有两个地址。
const book = (id, title, category, price, stock, tags, published = true) =>
({ _id: id, title, category, price: NumberInt(price), stock: NumberInt(stock), tags, published });
db.books.insertMany([
book("book-mongodb", "MongoDB 从入门到实践", "数据库", 89, 20, ["MongoDB", "后端"]),
book("book-design", "数据建模的艺术", "数据库", 79, 8, ["建模", "架构"]),
book("book-sql", "关系数据库十二讲", "数据库", 69, 12, ["SQL", "后端"]),
book("book-node", "Node.js 项目开发", "编程", 69, 15, ["Node.js", "后端"]),
book("book-web", "现代 Web 基础", "编程", 59, 30, ["Web", "前端"]),
book("book-go", "Go 并发实践", "编程", 79, 3, ["Go", "后端"]),
book("book-river", "纸上的河流", "文学", 49, 1, ["散文"]),
book("book-draft", "尚未发布的草稿", "草稿", 0, 0, [], false)
]);
db.customers.insertMany([
{ _id: "customer-lin", name: "林晓舟", email: "lin@example.com",
addresses: [{ label: "家", city: "上海", detail: "静安区纸舟路 8 号" }] },
{ _id: "customer-zhou", name: "周雨", email: "zhou@example.com",
addresses: [{ label: "家", city: "杭州", detail: "西湖区云栖街 12 号" }] },
{ _id: "customer-wang", name: "王青", email: "wang@example.com",
addresses: [{ label: "家", city: "成都", detail: "锦江区书香巷 5 号" }] },
{ _id: "customer-chen", name: "陈帆", email: "chen@example.com",
addresses: [
{ label: "家", city: "深圳", detail: "南山区桂湾路 3 号" },
{ label: "公司", city: "广州", detail: "天河区花城大道 66 号" }
] }
]);地址嵌在顾客文档里,因为总随顾客一起读。第三段是订单,line 生成明细,order 生成订单并算出 total:
const line = (bookId, title, unitPrice, quantity) =>
({ bookId, title, unitPrice: NumberInt(unitPrice), quantity: NumberInt(quantity) });
const order = (id, customerId, status, items, day) => ({
_id: id, customerId, status, items,
total: NumberInt(items.reduce((s, i) => s + i.unitPrice * i.quantity, 0)),
createdAt: ISODate(`2026-07-${day}T10:00:00Z`)
});
db.orders.insertMany([
order("order-1001", "customer-lin", "paid",
[line("book-mongodb", "MongoDB 从入门到实践", 99, 1), line("book-node", "Node.js 项目开发", 69, 1)], "01"),
order("order-1002", "customer-zhou", "paid",
[line("book-design", "数据建模的艺术", 79, 2)], "02"),
order("order-1003", "customer-lin", "shipped",
[line("book-mongodb", "MongoDB 从入门到实践", 89, 2)], "03"),
order("order-1004", "customer-wang", "pending",
[line("book-web", "现代 Web 基础", 59, 3)], "04"),
order("order-1005", "customer-zhou", "paid",
[line("book-mongodb", "MongoDB 从入门到实践", 89, 1), line("book-design", "数据建模的艺术", 79, 1)], "05"),
order("order-1006", "customer-wang", "cancelled",
[line("book-go", "Go 并发实践", 79, 1)], "06"),
order("order-1007", "customer-lin", "paid",
[line("book-river", "纸上的河流", 49, 1), line("book-web", "现代 Web 基础", 59, 1)], "07"),
order("order-1008", "customer-zhou", "shipped",
[line("book-sql", "关系数据库十二讲", 69, 1)], "08")
]);
print(EJSON.stringify({
books: db.books.countDocuments({}),
customers: db.customers.countDocuments({}),
orders: db.orders.countDocuments({})
}));订单里的 customerId、bookId 是引用,title 和 unitPrice 是下单时抄下来的快照:book-mongodb 首发卖 99,7 月 2 日降到 89,所以 1001 的快照是 99。金额用整数元,只为让你能心算核对,真实系统怎么存钱第 7 章再谈。时间是 UTC 的 ISODate,东八区加 8 小时。

运行脚本:
docker exec paperboat-mongo mongosh --quiet bookstore /scripts/seed.js{"books":8,"customers":4,"orders":8}seed.js 会删除三个集合再重建。可以反复跑,随时回到初始状态;绝不要对有真实数据的库执行。
再验证类型:
db.orders.aggregate([{ $match: { _id: "order-1001" } },
{ $project: { _id: 0, items: { $type: "$items" }, total: { $type: "$total" }, createdAt: { $type: "$createdAt" } } }])
db.orders.findOne({ _id: "order-1001" }).createdAt instanceof Date[ { items: 'array', total: 'int', createdAt: 'date' } ]
truecreatedAt 是真正的日期,total 是 int,之后的范围查询和按日分组才可靠。
校验器拦住坏订单
校验器在服务器上执行,写入来自哪里都一样。下面这张订单缺 customerId,items 又是空数组:
try {
db.orders.insertOne({ _id: "order-bad", status: "paid", items: [], total: NumberInt(0), createdAt: new Date() });
} catch (e) {
print(e.code);
print(e.errInfo.details.schemaRulesNotSatisfied.map(r => r.operatorName));
print(e.errInfo.details.schemaRulesNotSatisfied[1].missingProperties);
}
print(db.orders.countDocuments({ _id: "order-bad" }));121
[ 'properties', 'required' ]
[ 'customerId' ]
0121 是文档校验失败。properties 指出 items 违反 minItems,required 指出缺 customerId,最后的 0 证明坏订单没溜进去。不用 try,shell 会直接打印 MongoServerError: Document failed validation 加详情。
类型也会被查:unitPrice 写成 Double(69),肉眼看是 69,校验器照样拒绝(详情里是 consideredType: 'double')。默认策略是严格检查并拒绝(validationLevel: "strict",validationAction: "error");给已有数据的集合加规则时可以放宽,第 7 章会用到。

试把同一份草稿的单价改成 Double、数量改成 0,逐组找出服务器会指出的两处问题。
第 2 题 · 判断题
第 3 题 · 多选题 · 选出所有正确项
第 4 题 · 单选题
第 5 题 · 填空题
第 6 题 · 单选题
第 7 题 · 单选题
书店现在有 8 本书、4 位顾客、8 张订单,订单有校验器把关,可日常操作还没学:新顾客何舟注册怎么办,卖出一本书库存怎么减,草稿怎么安全删除?第 4 章从这些问题开始。