Skip to main content

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 + extensible BaseField
  • 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) and auto_now_add=True
  • Attribute access โ€” user.name instead of user["name"]
  • Serialization โ€” to_mongo() and from_mongo() for round-trip conversion
  • Abstract models & inheritance โ€” share fields across model hierarchies

๐Ÿ“ฆ Installation

# Clone the repository
git clone https://github.com/yourusername/MongoForge.git
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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

mongoforge_odm-0.1.0.tar.gz (13.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

mongoforge_odm-0.1.0-py3-none-any.whl (13.8 kB view details)

Uploaded Python 3

File details

Details for the file mongoforge_odm-0.1.0.tar.gz.

File metadata

  • Download URL: mongoforge_odm-0.1.0.tar.gz
  • Upload date:
  • Size: 13.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.4

File hashes

Hashes for mongoforge_odm-0.1.0.tar.gz
Algorithm Hash digest
SHA256 fe62c4eb6b34d81f699242efa79cd5f88342956236cc0bf910fee98046d9d486
MD5 66efcd2812037b68168c94c638772485
BLAKE2b-256 2b2ea3b0cc1183bdf9911a9bec581849f81bb8952220395f9fc12e7d69e31fe1

See more details on using hashes here.

File details

Details for the file mongoforge_odm-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: mongoforge_odm-0.1.0-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

Hashes for mongoforge_odm-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 c942de478a9bd3b4dd39eab0c2ba9e0dd4a12e18edbb792d5b874519d5efbf3b
MD5 2bb67e3c1049130d637dc5645c6c95f0
BLAKE2b-256 296a83120d813879cc0ad9a6ad1a710eb7d6f7c9986f0bed9f5d21ee61416dc8

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page