การตรวจสอบ schema ในตัวของ MongoDB
แม้ว่า MongoDB จะมี schema ที่ยืดหยุ่น แต่ก็มีฟังก์ชันสำหรับการตรวจสอบ schema ที่ครอบคลุมมาให้ในตัว เมื่อสร้าง collection คุณสามารถกำหนด JSON schema เพื่อระบุรูปแบบที่เอกสารควรปฏิบัติตามได้
หมายเหตุ: ที่นี่ใช้ชื่อ collection ที่สุ่มขึ้นมา เพื่อให้ทดลองส่งคำตอบได้หลายครั้งอย่างอิสระ
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
MongoDB เบื้องต้นใน Python
คำแนะนำการฝึกหัด
- ปรับการเรียก
.create_collection(): กำหนดให้titleเป็น"string" - แทรกข้อมูลภาพยนตร์ลงใน collection ที่เพิ่งสร้าง คือ
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(____)