Skip to content

MongoDB - 创建集合

在 MongoDB 中,集合 (collection) 是一组文档,类似于关系型数据库中的表。虽然 MongoDB 可以在您首次插入文档时隐式创建集合,但在生产环境中,最佳实践是显式创建它们,以便强制执行模式验证 (schema validation) 和其他配置。

您在 MongoDB Shell (mongosh) 中使用 db.createCollection(name, options) 方法来创建一个新集合。

db.createCollection( <name>, { <options> } )

name 是表示集合名称的字符串。options 是一个可选文档,用于指定配置。

字段类型描述
cappedboolean(可选) 如果为 true,则创建固定大小的集合 (capped collection),当达到最大大小时,它会自动覆盖最旧的条目。需要 size 选项。
sizenumber(可选) 指定固定大小集合的最大字节数。
maxnumber(可选) 指定固定大小集合中允许的最大文档数。
validatordocument(可选) 一个强大的功能,允许您为集合指定 JSON Schema 验证规则。违反这些规则的插入和更新将被拒绝。
validationLevelstring(可选) 确定在更新时验证器对现有文档的严格程度。可以是 "off"、"strict"(默认)或 "moderate"。
validationActionstring(可选) 确定是否 "error"(默认)并拒绝违反规则的文档,或者只是 "warn" 并记录违规。
collationdocument(可选) 指定用于字符串比较的语言特定规则,例如字母大小写和重音符号的规则。
> use my_new_db
switched to db my_new_db
> db.createCollection("users")
{ "ok" : 1 }
> show collections
users

2. 创建带模式验证的集合 (最佳实践)

Section titled “2. 创建带模式验证的集合 (最佳实践)”

这是生产系统推荐的方法。它确保数据一致性和质量。

> db.createCollection("students", {
validator: {
$jsonSchema: {
bsonType: "object",
required: [ "name", "year", "major", "gpa" ],
properties: {
name: {
bsonType: "string",
description: "must be a string and is required"
},
year: {
bsonType: "int",
minimum: 1,
maximum: 5,
description: "must be an integer in [1, 5] and is required"
},
major: {
bsonType: "string",
description: "must be a string and is required"
},
gpa: {
bsonType: ["double", "int"],
description: "must be a number and is required"
}
}
}
}
})
{ "ok" : 1 }

现在,如果您尝试插入一个不符合此模式的文档,MongoDB 将会拒绝:

> db.students.insertOne({ name: "John Doe", major: "Computer Science" })
// This will fail because 'year' and 'gpa' are missing.
MongoServerError: Document failed validation

如果您向一个不存在的集合插入文档,MongoDB 会自动为您创建它。这在开发过程中很方便,但不建议在生产环境中使用。

> db.logs.insertOne({ timestamp: new Date(), message: "User logged in." })
{
acknowledged: true,
insertedId: ObjectId("...")
}
> show collections
logs
students
users