Get startedGet started for free

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.

This exercise is part of the course

Introduction to MongoDB in Python

View Course

Exercise instructions

  • Adapt the .create_collection() call: title should be a "string".
  • Insert the movie into your newly minted movies collection, mov.
  • Inspect the result of the insertion to check it was successful.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# 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(____)
Edit and Run Code