Skip to content

MongoEngine

Data & AnalyticsDataPython

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 mongoengine

Getting started

The smallest useful thing you can do with it, and what each part means.

Connecting to MongoDB
from mongoengine import connect
connect('mydb')
Connects to a MongoDB database named 'mydb'. You can also specify host, port, username, and password.
Defining a simple document
from mongoengine import Document, StringField, IntField

class User(Document):
    name = StringField(required=True, max_length=50)
    age = IntField()
Defines a `User` document with `name` and `age` fields, including basic validation.
Creating a document
user = User(name='Alice', age=25)
user.save()
Creates a new `User` document and saves it to the database.

Advanced usage

Where the library earns its place over a simpler alternative.

Querying documents
users = User.objects(age__gte=18)
for user in users:
    print(user.name, user.age)
Fetches all users aged 18 or older using MongoEngine’s query syntax.
Updating documents
User.objects(name='Alice').update(set__age=26)
Updates the age of users named 'Alice' to 26.
Deleting documents
User.objects(name='Alice').delete()
Deletes all users with the name 'Alice'.
Embedded documents
from mongoengine import EmbeddedDocument, EmbeddedDocumentField

class Address(EmbeddedDocument):
    street = StringField()
    city = StringField()

class User(Document):
    name = StringField()
    address = EmbeddedDocumentField(Address)
Shows how to define embedded documents to represent nested structures.
Reference fields (relationships)
from mongoengine import ReferenceField

class Post(Document):
    title = StringField()
    author = ReferenceField(User)
Defines a relationship between `Post` and `User` documents using reference fields.

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.