Sling Academy
Home/Python/MongoEngine: How to define document’s schema

MongoEngine: How to define document’s schema

Last updated: February 09, 2024

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.

Next Article: MongoEngine: Working with ListField

Previous Article: MongoEngine: How to use multiple databases

Series: Data Persistence in Python – Tutorials & Examples

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots