What it is
MongoEngine is an Object-Document Mapper (ODM) for Python that provides a high-level abstraction for working with MongoDB. It allows developers to define schemas and interact with MongoDB documents using Python classes instead of raw queries.
MongoEngine allows you to define document schemas as Python classes, perform CRUD operations, build queries, and handle embedded documents and references. It integrates well with web frameworks like Flask and Django.
Installation
pip install mongoengineGetting started
The smallest useful thing you can do with it, and what each part means.
from mongoengine import connect
connect('mydb')from mongoengine import Document, StringField, IntField
class User(Document):
name = StringField(required=True, max_length=50)
age = IntField()user = User(name='Alice', age=25)
user.save()Advanced usage
Where the library earns its place over a simpler alternative.
users = User.objects(age__gte=18)
for user in users:
print(user.name, user.age)User.objects(name='Alice').update(set__age=26)User.objects(name='Alice').delete()from mongoengine import EmbeddedDocument, EmbeddedDocumentField
class Address(EmbeddedDocument):
street = StringField()
city = StringField()
class User(Document):
name = StringField()
address = EmbeddedDocumentField(Address)from mongoengine import ReferenceField
class Post(Document):
title = StringField()
author = ReferenceField(User)Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- ValidationError
- Occurs when a document fails field validation. Check field types, required fields, and constraints.
- NotUniqueError
- Raised when attempting to insert a document with a value that violates a unique constraint.
- DoesNotExist
- Thrown when querying for a document that does not exist. Use `.first()` or handle exceptions.
Best practices
- Use schema validation in your Document fields to prevent inconsistent data.
- Prefer query filters over iterating all documents for efficiency.
- Close the connection explicitly in long-running scripts using `disconnect()` if needed.
- Use indexes for frequently queried fields to improve performance.
- Leverage embedded documents for tightly coupled data and references for loosely coupled relationships.
Background
Why it exists, and what it was reacting to.
MongoEngine was created by Michael Bayer and others to provide a Pythonic interface for MongoDB, similar to how SQLAlchemy provides an ORM for SQL databases. It is widely used in Python web applications and projects requiring flexible NoSQL data storage, offering schema validation, query building, and relationship management.
