MongoEngine
MongoEngine is a Python Object-Document Mapper (ODM) for working with MongoDB. It provides a declarative schema definition, query builder, and features like document relationships, inheritance, and validation, making it easier to interact with MongoDB databases using Python objects. The library is actively maintained, with regular updates to support new PyMongo versions and introduce features, currently at version 0.29.3.
Warnings
- breaking Major 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`.
- breaking MongoEngine's compatibility with `pymongo` is crucial. Newer versions of MongoEngine often require specific `pymongo` versions, and upgrading `pymongo` independently can lead to issues.
- gotcha The `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.
- 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.
Install
-
pip install mongoengine
Imports
- Document
from mongoengine import Document
- StringField
from mongoengine import StringField
- connect
from mongoengine import connect
- ValidationError
from mongoengine.errors import ValidationError
Quickstart
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')