A Django-inspired MongoDB ODM for Python
Project description
๐ง MongoForge
A Django-inspired MongoDB ODM for Python โ define document schemas as classes with typed fields, validate data automatically, and perform CRUD operations through a clean manager API.
Built on PyMongo.
โจ Features
- Declarative schemas โ define documents as Python classes with typed fields
- 10 built-in field types โ
StringField,IntField,FloatField,BoolField,ListField,DateTimeField,DictField,ObjectIdField,EmbeddedField+ extensibleBaseField - Rich validation โ required, min/max length, min/max value, regex, choices, custom validators
- Metaclass magic โ automatic field collection, inheritance, collection naming
- Manager API โ
create,bulk_create,all,first,get,filter,count,update,update_one,update_many,delete_one,delete_many - Django-style filter operators โ
age__gte=18,name__in=[...],status__ne="inactive"(supports:gt,gte,lt,lte,ne,in,nin) - Auto timestamps โ
DateTimeField(auto_now=True)andauto_now_add=True - Attribute access โ
user.nameinstead ofuser["name"] - Serialization โ
to_mongo()andfrom_mongo()for round-trip conversion - Abstract models & inheritance โ share fields across model hierarchies
๐ฆ Installation
# Clone the repository
git clone https://github.com/Sourabh7singh/MongoForge
cd MongoForge
# Create and activate a virtual environment
python -m venv env
env\Scripts\activate # Windows
# source env/bin/activate # macOS/Linux
# Install dependencies
pip install pymongo python-dotenv python-slugify
# For running tests (no live MongoDB needed)
pip install pytest mongomock
Environment Setup
Create a .env file in the project root:
MONGO_URI=mongodb://localhost:27017/
DATABASE_NAME=mongoforge
๐ Quick Start
Define a Model
from mongoforge import MongoForge
from mongoforge.fields import StringField, IntField, BoolField, DateTimeField, ListField
class User(MongoForge):
name = StringField(required=True, min_length=2, max_length=100)
email = StringField(required=True, regex=r"^[\w.+-]+@[\w-]+\.[\w.-]+$")
age = IntField(min_value=0, max_value=150)
is_admin = BoolField(default=False)
tags = ListField(StringField())
created = DateTimeField(auto_now_add=True)
updated = DateTimeField(auto_now=True)
class Meta:
collection = "users"
Create & Validate
user = User(name="Saurabh", email="saurabh@example.com", age=25)
# Validate before saving
user.validate() # raises ValidationError if invalid
# Serialize to MongoDB document
doc = user.to_mongo()
# Insert into database
User.objects.create(doc)
Query
# Get all documents
User.objects.all() # โ list[dict]
# Filter with operators
User.objects.filter(age__gte=18) # age >= 18
User.objects.filter(name__in=["Alice", "Bob"])
# Get single document
User.objects.get({"email": "saurabh@example.com"})
# Count
User.objects.count()
Update & Delete
# Update by ID
User.objects.update(id="...", update_data={"name": "Updated Name"})
# Update many
User.objects.update_many({"age": {"$gte": 30}}, {"is_admin": True})
# Delete
User.objects.delete_one({"name": "Alice"})
User.objects.delete_many({"age": {"$lt": 18}})
Validation in Action
from mongoforge.exceptions import ValidationError
user = User(name="A", email="not-an-email", age=-5)
try:
user.validate()
except ValidationError as exc:
print(exc)
# Validation failed. name: Minimum length is 2; email: Value does not match regex ...; age: Minimum value is 0
print(exc.errors)
# {'name': ['Minimum length is 2'], 'email': ['Value does not match regex ...'], 'age': ['Minimum value is 0']}
๐ Field Types
| Field | Python Type | Extra Options |
|---|---|---|
StringField |
str |
min_length, max_length, regex |
IntField |
int |
min_value, max_value |
FloatField |
float |
โ |
BoolField |
bool |
โ |
ListField |
list |
field (inner field for item validation) |
DateTimeField |
datetime |
auto_now, auto_now_add |
DictField |
dict |
โ |
ObjectIdField |
ObjectId |
Auto-generates if None |
EmbeddedField |
dict |
document_class (stub โ Phase 4) |
Common options (all fields): required, default, unique, choices, validators, null
๐๏ธ Architecture
Model Class โ MongoForgeMeta (metaclass) โ collects fields + attaches MongoManager
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โผ
MongoManager (cls.objects)
โโโ CreateMixin โ create(), bulk_create()
โโโ ReadMixin โ all(), first(), get(), filter(), count()
โโโ UpdateMixin โ update(), update_one(), update_many()
โโโ DeleteMixin โ delete_one(), delete_many()
๐งช Running Tests
Tests use mongomock โ no live MongoDB required.
# With venv activated
python -m pytest mongoforge/tests/ -v
# Or using venv python directly
env\Scripts\python.exe -m pytest mongoforge/tests/ -v
148 tests covering:
- All 10 field types + validation paths
- Model instances, attribute access, serialization
- Metaclass, inheritance, abstract models
- Full CRUD operations + filter operators
- Exception hierarchy + formatting
๐บ๏ธ Roadmap
| Phase | Description | Status |
|---|---|---|
| Phase 1 | Fields & Schema | โ ~95% |
| Phase 2 | QuerySet (chainable queries) | โฌ Not started |
| Phase 3 | Model Lifecycle (save(), delete(), reload(), dirty tracking) |
๐ถ ~50% |
| Phase 4 | Relationships (EmbeddedDocument, ReferenceField) | โฌ Not started |
| Phase 5 | Indexes, Middleware & CLI | โฌ Not started |
| Phase 6 | Packaging & Developer Experience | ๐ถ ~30% |
See implementation_plan.md for the full roadmap with target APIs.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file mongoforge_odm-0.1.1.tar.gz.
File metadata
- Download URL: mongoforge_odm-0.1.1.tar.gz
- Upload date:
- Size: 12.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b2329f35264753e3069dff4f623acf9038f34bd6b622d9d70754de34168984d5
|
|
| MD5 |
f4b7740f8c57d87ddd6a52525fbb64e0
|
|
| BLAKE2b-256 |
8eb1e1842a46eba82775b365773e1014941a37f56793f4205c64e66607558b6d
|
File details
Details for the file mongoforge_odm-0.1.1-py3-none-any.whl.
File metadata
- Download URL: mongoforge_odm-0.1.1-py3-none-any.whl
- Upload date:
- Size: 13.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
17dd2e2b224e46a433b29b6abb7be4c80d369f0d4e14d19e93e9c0fd43617e81
|
|
| MD5 |
7cefbd34b7a226b772baadbed17bb552
|
|
| BLAKE2b-256 |
8a97dc3e50dcbf001f0393591f0f97686cc7de2227538983fbecf7c05af762bf
|