MongoDB's built-in schema validation
Even though MongoDB has a flexible schema, it also comes pre-packed with extensive functionality for schema validation. When creating a collection, you can specify a JSON schema to describe what format documents should follow.
Note: we're using a randomly generated collection name here, so that you can freely experiment with multiple submissions.
Este ejercicio forma parte del curso
Introduction to MongoDB in Python
Instrucciones del ejercicio
- Adapt the .create_collection() call:titleshould be a"string".
- Insert the movie into your newly minted movies collection, mov.
- Inspect the result of the insertion to check it was successful.
Ejercicio interactivo práctico
Prueba este ejercicio y completa el código de muestra.
# 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(____)