MongoDB का बिल्ट-इन स्कीमा वेलिडेशन
भले ही MongoDB का स्कीमा लचीला हो, इसमें स्कीमा वेलिडेशन के लिए पहले से ही व्यापक फ़ंक्शनैलिटी मौजूद है. कलेक्शन बनाते समय, आप एक JSON स्कीमा स्पेसिफाई कर सकते हैं जो बताएगा कि डॉक्युमेंट्स को किस फ़ॉर्मेट का पालन करना चाहिए.
नोट: यहाँ हम रैंडमली जनरेट किया गया कलेक्शन नाम इस्तेमाल कर रहे हैं, ताकि आप कई सबमिशन के साथ बेझिझक प्रयोग कर सकें.
यह अभ्यास पाठ्यक्रम का हिस्सा है
Python में MongoDB परिचय
अभ्यास निर्देश
.create_collection() कॉल को एडाप्ट करें:titleएक"string"होना चाहिए.- अपनी नई बनी मूवीज़ कलेक्शन
movमें मूवी insert करें. - इन्सर्शन के परिणाम को देखें और जाँचें कि यह सफल रहा.
इंटरैक्टिव व्यावहारिक अभ्यास
इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।
# 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(____)