MongoEngine

Language: Python

Data

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.

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.

Installation

pip: pip install mongoengine
conda: conda install -c conda-forge mongoengine

Usage

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.

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.

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.

Error Handling

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.