Introduction to MongoDB in Python
Filip Schouwenaars
Machine Learning Researcher
mov.insert_one({ "title": "knives out", "genre": ["comedy", "crime", "drama"], "year": 2019, # oops "rating": 7.9, })
mov.find_one({ "title": "knives out", "release_year": 2019 })
from pydantic import BaseModel
from typing import Optional
class Movie(BaseModel):
title: str
genre: list[str]
release_year: int
rating: float
won_oscar: Optional[bool] = None
# Before
new_movie = {
"title": "knives out",
"genre": ["comedy", "crime", "drama"],
"year": 2019, # oops
"rating": 7.9,
}
# No output
# Now
new_movie = Movie(
title = "knives out",
genre = ["comedy", "crime", "drama"],
year = 2019, # oops
rating = 7.9,
)
pydantic.error_wrappers.ValidationError:
1 validation error for Movie
release_year: field required
from pydantic import BaseModel
from typing import Optional
class Movie(BaseModel):
title: str
genre: list[str]
release_year: int
rating: float
won_oscar: Optional[bool] = None
# Correct set of fields and field values new_movie = Movie( title = "knives out", genre = ["comedy", "crime", "drama"], release_year = 2019, rating = 7.9, )
mov.insert_one(dict(new_movie))
InsertOneResult(...)
client.film.create_collection(
"movies_v2",
validator={
"$jsonSchema": {
"required": ["title", "genre", "release_year", "rating"],
"properties": {
"title": { "bsonType": "string" },
"genre": {
"bsonType": "array",
"items": { "bsonType": "string" }
},
"release_year": { "bsonType": "int" },
"rating": { "bsonType": "double" },
"won_oscar": { "bsonType": "bool" }
}
}
}
)
client.film.movies_v2.insert_one({
"title": "knives out",
"genre": ["comedy", "crime", "drama"],
"year": 2019, # oops
"rating": 7.9,
})
pymongo.errors.WriteError: Document failed validation, [...]
'missingProperties': ['release_year'], 'errmsg': 'Document failed validation'}
pydantic.BaseModel
Introduction to MongoDB in Python