MongoDB 的内置架构验证
尽管 MongoDB 采用灵活的架构,但它也内置了强大的架构验证功能。 创建集合时,您可以指定一个 JSON 架构,用来描述文档应符合的格式。
注意:这里我们使用随机生成的集合名称,方便您多次提交并自由尝试。
本练习是课程的一部分
Python 中的 MongoDB 入门
练习说明
- 调整
.create_collection() 的调用:将title指定为"string"。 - 将该电影插入到您新创建的电影集合
mov中。 - 查看插入结果,检查是否成功。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Create collection with schema spec
mov = client.film.create_collection(
f"movies_{random.randint(1, 100)}",
validator={
"$jsonSchema": {
"required": ["title", "genre", "release_year", "rating"],
"properties": {
"title": { "bsonType": ____ },
"genre": {
"bsonType": "array",
"items": { "bsonType": "string" }
},
"release_year": { "bsonType": "int" },
"rating": { "bsonType": "double" },
"won_oscar": { "bsonType": "bool" }
}
}
}
)
# Insert movie
res = mov.____({
"title": "the avengers",
"genre": ["action", "adventure", "sci-fi"],
"release_year": 2012,
"rating": 8.0
})
# Print result
print(____)