Sling Academy
Home/Python/MongoEngine ReferenceField – Tutorial & Examples

MongoEngine ReferenceField – Tutorial & Examples

Last updated: February 10, 2024

Introduction

With the evolution of NoSQL databases, MongoDB has emerged as a leading technology for managing document-oriented data. The Python community has developed MongoEngine, an Object-Document Mapper (ODM), facilitating interactions with MongoDB through Pythonic objects. One powerful feature of MongoEngine is the ReferenceField, enabling relationships between documents. This tutorial will guide you through the use of ReferenceField in MongoEngine, illustrated with examples ranging from basic to advanced.

More Details about ReferenceField

The ReferenceField allows one document to reference another in your database, akin to foreign keys in a relational database system but adapted for the document model. This is crucial for representing relationships like users and their posts, books and authors, etc.

Setup and Basic Example

To start exploring ReferenceField, you first need a running MongoDB instance and MongoEngine installed in your Python environment:

pip install mongoengine

Next, define two simple models to see ReferenceField in action. Let’s model Authors and Books:

from mongoengine import Document, StringField, ReferenceField, connect
connect('mongoengine_test_db')

class Author(Document):
    name = StringField(required=True)

class Book(Document):
    title = StringField(required=True)
    author = ReferenceField(Author)

With the models defined, let’s create an Author and reference this author in a Book:

# Creating an author
author = Author(name='J.K. Rowling').save()

# Creating a book with a reference to the author
book = Book(title='Harry Potter and the Philosopher's Stone', author=author).save()

# Retrieving the book along with its author
doc = Book.objects.first()
print(f"Title: {doc.title}, Author: {doc.author.name}")

Output:

Title: Harry Potter and the Philosopher's Stone, Author: J.K. Rowling

Querying Reference Fields

Querying documents through ReferenceField showcases its true power. You can filter books by authors or vice versa.

# Find all books by J.K. Rowling
books = Book.objects(author=author)
for book in books:
    print(book.title)

This demonstrates how ReferenceField can be used to intuitively navigate relationships between documents.

Advanced Use of ReferenceField

Moving toward more complex examples, consider embedding a list of references. This is useful for modeling many-to-many relationships, such as a book belonging to multiple categories.

from mongoengine import ListField

class Category(Document):
    name = StringField(required=True)

class Book(Document):
    title = StringField(required=True)
    categories = ListField(ReferenceField(Category))

Here, a book can be tagged with multiple categories, enriching the document’s relational data model.

Dealing with Deletion

Careful handling of document deletion when using ReferenceField is crucial. MongoEngine does not automatically delete references, to prevent data loss. It’s crucial to implement deletion logic that respects your application’s data integrity, possibly by also deleting or nullifying references when a document is removed.

Conclusion

This tutorial introduced the fundamentals of using ReferenceField in MongoEngine, illustrating how to define relationships between documents and efficiently query them. Through our examples, we’ve seen how ReferenceField enriches the capabilities of MongoDB databases in representing complex, related data structures, offering an invaluable tool for developers working in document-oriented database environments.

Next Article: MongoEngine: How to append item to a ListField

Previous Article: MongoEngine: How to see the generated query

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