MongoEngine: How to define document’s schema

Updated: February 9, 2024 By: Guest Contributor Post a comment

Introduction

MongoEngine is a Document-Object Mapper (DOM) for working with MongoDB from Python. It translates Python classes to MongoDB documents, and vice versa, allowing for a more intuitive way of working with MongoDB. Defining document schemas is at the heart of using MongoEngine effectively. In this tutorial, we will cover how to define document schemas using MongoEngine with various examples from basic to advanced.

Basic Document Definition

To start, here is a simple document definition in MongoEngine:

from mongoengine import Document, StringField

class User(Document):
    name = StringField(required=True)
    email = StringField(required=True)

This code defines a User document with two fields: name and email, both of which are strings and required.

Advanced Fields

MongoEngine supports various field types, allowing for rich schema definitions. Here are a few examples:

from mongoengine import Document, StringField, IntField, DateTimeField, ListField, EmbeddedDocument, EmbeddedDocumentField

class Comment(EmbeddedDocument):
    content = StringField()
    date_posted = DateTimeField(default=datetime.utcnow)

class Post(Document):
    title = StringField(required=True)
    content = StringField(required=True)
    author = StringField(required=True)
    comments = ListField(EmbeddedDocumentField(Comment))
    views = IntField(default=0)

This example shows a Post document with embedded Comment documents, demonstrating the use of EmbeddedDocument and EmbeddedDocumentField.

Indexing and Optimizations

We can also define indexes for our documents to improve query performance:

from mongoengine import Document, StringField, EmailField

class User(Document):
    name = StringField(required=True)
    email = EmailField(required=True, unique=True)
    meta = {'indexes': [
        {'fields': ['email'], 'unique': True}
    ]}

This User document specifies an index on the email field to ensure uniqueness.

Dynamic Documents

For schemas that need flexibility, MongoEngine offers DynamicDocument. Here’s how you can use it:

from mongoengine import DynamicDocument, StringField

class BlogPost(DynamicDocument):
    title = StringField(required=True)

DynamicDocument allows for undefined fields to be set on the document, adding flexibility to the schema definition.

Conclusion

Defining document schemas is a cornerstone of working with MongoDB via MongoEngine in Python. By leveraging MongoEngine’s rich field types and document classes, you can create expressive and efficient data models that align with your application’s needs.