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.
pip install mongoengineconda install -c conda-forge mongoengineMongoEngine 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.
from mongoengine import connect
connect('mydb')Connects to a MongoDB database named 'mydb'. You can also specify host, port, username, and password.
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.
user = User(name='Alice', age=25)
user.save()Creates a new `User` document and saves it to the database.
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.
User.objects(name='Alice').update(set__age=26)Updates the age of users named 'Alice' to 26.
User.objects(name='Alice').delete()Deletes all users with the name 'Alice'.
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.
from mongoengine import ReferenceField
class Post(Document):
title = StringField()
author = ReferenceField(User)Defines a relationship between `Post` and `User` documents using reference fields.
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.