How to Create a MongoDB Schema in Python?

Estimated read time 3 min read

In MongoDB, the concept of a strict schema like in traditional SQL databases doesn’t exist. MongoDB is a schema-less database, which means that documents within a collection can have different structures and fields. However, you can define a schema in your Python application to enforce a certain structure and validation on your data.

To create a MongoDB schema in Python, you can use the Schema class provided by the pymongo_schema library. Here’s an example that demonstrates how to define and use a schema:

First, make sure you have the pymongo_schema library installed by running the following command:

pip install pymongo-schema
from pymongo import MongoClient
from pymongo_schema import Schema, validators

# Define the schema
schema = Schema(
        'name': str,
        'age': validators.Int(min_value=0),
        'email': validators.Email()

# Establish a connection to MongoDB
client = MongoClient('mongodb://localhost:27017')

# Access the database and collection
db = client['your_database_name']
collection = db['your_collection_name']

# Insert a document using the schema
document = {
    'name': 'John',
    'age': 25,
    'email': ''

if schema.validate(document):
    print("Document inserted successfully.")
    print("Document validation failed.")

# Query documents using the schema
documents = collection.find({})
for document in documents:
    if schema.validate(document):
        print("Invalid document found.")

# Update a document using the schema
updated_data = {
    'age': 30,
    'email': ''

if schema.validate(updated_data):
    collection.update_one({'name': 'John'}, {'$set': updated_data})
    print("Document updated successfully.")
    print("Updated document validation failed.")

In the above code:

  1. First, you import the necessary modules: MongoClient from pymongo and Schema along with validators from pymongo_schema.
  2. Then, you define the schema using the Schema class, specifying the fields and their corresponding data types. You can also use validators to add additional constraints and validation rules to the fields. In the example, the age field is validated to be an integer with a minimum value of 0, and the email field is validated to be a valid email address.
  3. After establishing a connection to MongoDB, you access the desired database and collection.
  4. When inserting a document, you can validate it against the defined schema using the validate method of the schema object. If the document passes the validation, it is inserted into the collection.
  5. When querying documents, you can iterate over the result and validate each document using the validate method before processing it.
  6. When updating a document, you can validate the updated data against the schema before performing the update.

Make sure to replace 'your_database_name' and 'your_collection_name' with the actual names of your database and collection. Customize the schema fields and validation rules based on your specific requirements.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply