Install & Compatibility
Where this runs
tested against v0.29.3 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.516s · 26.7MB
glibcpy 3.10–3.95 runs
installs and imports cleanly · install 2.7s · import 0.462s · 29MB
27MB installed
● package 27MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
Document
✓ from mongoengine import Document
StringField
✓ from mongoengine import StringField
connect
✓ from mongoengine import connect
ValidationError
✓ from mongoengine.errors import ValidationError
✗ from mongoengine import ValidationError
As of v0.27.0, ValidationError moved from the top-level `mongoengine` module to `mongoengine.errors`.
This quickstart demonstrates defining a `Document` model, connecting to a MongoDB instance, creating, saving, finding, updating, and deleting documents. It highlights the use of `StringField` and basic query operations with `User.objects`.
import os
from mongoengine import Document, StringField, connect
# Connect to MongoDB (replace with your connection string)
# Use os.environ.get for secure, flexible credentials
mongo_uri = os.environ.get('MONGO_URI', 'mongodb://localhost:27017/testdb')
connect(alias='default', host=mongo_uri)
class User(Document):
name = StringField(required=True, max_length=50)
email = StringField(required=True, unique=True)
meta = {'collection': 'users'}
# Create a new user
user = User(name='Alice Wonderland', email='alice@example.com')
user.save()
print(f"Saved user: {user.name} with ID: {user.id}")
# Find a user by email
alice = User.objects(email='alice@example.com').first()
if alice:
print(f"Found user: {alice.name}")
# Update a user
alice.name = 'Alice W.'
alice.save()
print(f"Updated user: {alice.name}")
# Delete a user
alice.delete()
print(f"User '{alice.email}' deleted.")
# Clean up (optional: disconnect)
# disconnect_all() # Or use disconnect('default')
Debug
Known issues
breakingMajor changes were introduced in v0.20.0, especially regarding how `ObjectId` instances are handled and the default behavior of `ReferenceField`. For example, `ReferenceField.db_field` was renamed to `reverse_delete_rule`.fixReview the official release notes for v0.20.0 (and subsequent major versions like 0.25.0, 0.27.0) and update your models and queries accordingly. Pay close attention to `ReferenceField` definitions and `ObjectId` comparisons.
affects: >=0.20.0
breakingMongoEngine's compatibility with `pymongo` is crucial. Newer versions of MongoEngine often require specific `pymongo` versions, and upgrading `pymongo` independently can lead to issues.fixAlways install `mongoengine` and let it pull its compatible `pymongo` version. If you need a specific `pymongo` version, check MongoEngine's `setup.py` or release notes for tested compatibility. For example, v0.29.1 added support for `pymongo` 4.9.
affects: All versions, especially when upgrading either library.
gotchaThe `connect` function takes an `alias` parameter which defaults to 'default'. When managing multiple database connections, explicitly provide unique aliases to prevent conflicts and ensure operations are directed to the correct database.fixUse `connect(alias='my_db_alias', host='...')` and specify the alias in `Document.meta = {'db_alias': 'my_db_alias'}` or when querying/saving documents. affects: All versions
gotcha`Document.save()` performs both inserts and updates. If a document has an `id` (or `_id`) field, `save()` will attempt an update; otherwise, it will perform an insert. This can lead to unexpected updates if an `id` is accidentally set before the first save, or new documents not being inserted if an existing ID is reused.fixBe mindful of how `id` fields are managed. For new documents, ensure the `id` field is not set before the first `save()`. To force an insert or update, consider using `insert()` or `update()` methods explicitly if your use case requires it, or `update_one()` with `upsert=True`.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'mongoengine'
The mongoengine library has not been installed in your Python environment, or the Python interpreter running the code cannot find the installed package.
fixEnsure mongoengine is installed using pip: `pip install mongoengine`. If using a virtual environment, activate it first. If running with `sudo`, ensure it's installed for the root Python environment or run without `sudo` if possible.
mongoengine.connection.ConnectionError: You have not defined a default connection
MongoEngine requires an active connection to a MongoDB database before performing operations, and no default connection has been established.
fixEstablish a connection to your MongoDB instance using `mongoengine.connect()` before defining or interacting with documents. Example: `from mongoengine import connect; connect(db='your_database_name', host='localhost', port=27017)`
mongoengine.errors.ValidationError: (DocumentName:None) (Field is required: ['field_name'])
A required field in your MongoEngine Document definition was not provided when attempting to create or save a document instance.
fixEnsure all `required=True` fields are provided with a valid value when initializing or saving a document. Example: `MyDocument(required_field='value').save()`
mongoengine.errors.NotRegistered: 'DocumentName' has not been registered in the document registry
This error typically occurs when a Document class is referenced (e.g., in a `ReferenceField`) before it has been imported and registered with MongoEngine, often due to circular imports or improper import order.
fixEnsure all Document classes are imported before they are referenced. For `ReferenceField` definitions, use a string literal of the document name (e.g., `ReferenceField('User')`) to avoid circular imports, and make sure the referenced Document is imported elsewhere in your application. mongoengine.errors.FieldDoesNotExist: The fields "{'field_name'}" do not exist on the document "DocumentName"
You are attempting to set or query a field on a MongoEngine Document that is not defined in its schema, or there's a typo in the field name.
fixVerify that `field_name` is correctly defined in your Document class. If you intend to store dynamic fields not explicitly in the schema, use `DynamicDocument` instead of `Document`, or set `strict=False` in the `meta` dictionary if you only want to ignore extra fields on load.
Upgrade
Version history
0.29.3latest on PyPI · released Mar 10, 2026
Audit
Dependencies
pymongorequiredOfficial MongoDB Python driver; MongoEngine builds on top of it for database interaction.