Skip to main content

gdmongolite is a zero-boilerplate, schema-first, multi-driver MongoDB toolkit that unifies synchronous and asynchronous drivers, Pydantic-powered validation, automatic migrations, telemetry hooks, and a full CLI—all in one package. You write only your data models and queries; gdmongolite handles the rest.

Project description

gdmongolite Documentation

gdmongolite is a zero-boilerplate, schema-first, multi-driver MongoDB toolkit that unifies synchronous and asynchronous drivers, Pydantic-powered validation, automatic migrations, telemetry hooks, and a full CLI—all in one package. You write only your data models and queries; gdmongolite handles the rest.

Table of Contents

  1. Installation
  2. Configuration
  3. Defining Schemas
  4. Connecting to MongoDB
  5. CRUD Operations
  6. Automatic Migrations
  7. Interactive Shell
  8. Model Generation
  9. Telemetry Hooks
  10. CLI Reference
  11. Testing
  12. Project Layout
  13. Best Practices
  14. FAQ

1. Installation

Install the latest release from PyPI:

pip install gdmongolite

For development tools (linters, test frameworks):

pip install gdmongolite[dev]

2. Configuration

gdmongolite loads MongoDB connection settings from a .env file or environment variables. Create .env in your project root:

MONGO_URI="mongodb://localhost:27017"
MONGO_DB="myapp"
MONGO_MAX_POOL=50
MONGO_MIN_POOL=5
MONGO_TIMEOUT_MS=30000

Alternatively, set environment variables directly:

export MONGO_URI="mongodb://db.example.com:27017"

gdmongolite uses these settings automatically—no additional code required.

3. Defining Schemas

All your data models inherit from Schema. Collections are named automatically (snake_case of the class name).

# src/gdmongolite/schema/__init__.py
from gdmongolite import DB, Schema, Email, Positive

# Create or reuse the default DB instance
db = DB()

class User(Schema):
    """User document with validation"""
    name: str               # any non-empty string
    email: Email            # must match email format
    age: Positive()         # must be > 0
    tags: list[str] = []    # default to empty list

# After definition, db.User refers to this class
assert db.User is User

Behind the scenes, gdmongolite:

  • Inherits Pydantic’s validation
  • Binds User to the user collection
  • Adds built-in CRUD methods

4. Connecting to MongoDB

Import and instantiate the singleton façade:

from gdmongolite import DB

# Uses .env or env vars; auto-detects sync/async context
db = DB()

# Or explicitly sync or async:
db_sync = DB(mode="sync")
db_async = DB(mode="async")

# Manually specify URI:
db_custom = DB("mongodb://localhost:27017", database="testdb")

Close connections when done:

await db.close()         # async
db_sync.close_sync()     # sync

5. CRUD Operations

gdmongolite exposes simple, consistent methods on each Schema subclass.

Operation Async Example Sync Example
Insert one await db.User.insert({"name":"Alice","email":"a@b.com","age":30}) db.User.insert_sync({...})
Find many await db.User.find(age__gte=18).to_list() db.User.find(age__gte=18).to_list_sync()
Update one await db.User.update({"_id": id}, {"age":31}) db.User.update_sync({...}, {...})
Delete many await db.User.delete(age__lt=13) db.User.delete_sync(age__lt=13)
Every operation returns a QueryResponse:
{
  "success": True,
  "data": [...],       # inserted IDs or found documents
  "count": 3,
  "message": "Found 3 documents"
}

6. Automatic Migrations

When your schemas change (add/remove fields or indexes), generate migration scripts:

gdmongolite migrate
  • Compares current schema definitions to the live database
  • Creates timestamped Python scripts in migrations/
  • Apply migrations automatically at startup or manually:
await db.migrate_all()

7. Interactive Shell

Launch a REPL pre-loaded with db and your schemas:

gdmongolite shell

Inside:

>>> await db.User.insert({"name":"Bob","email":"bob@x.com","age":25})
>>> users = await db.User.find().to_list()
>>> print(users)

8. Model Generation

Scaffold a Python schema from an existing collection:

gdmongolite gen-model \
  --collection products \
  --out src/models/product.py
  • Samples document fields and types
  • Generates a Product(Schema) class with inferred attributes

9. Telemetry Hooks

Monitor or instrument queries by registering hooks:

from gdmongolite import DB

@DB.on("pre_query")
def before_query(collection, filt, opts):
    print(f"Querying {collection}: {filt}")

@DB.on("post_query")
def after_query(collection, result):
    print(f"{collection} returned {result.count} docs in {result.duration}ms")

Supported events: pre_query, post_query, pre_insert, post_insert, etc. Integrate with any metrics or logging system.

10. CLI Reference

gdmongolite --help
Command Description
migrate Generate and apply migration scripts
shell Launch interactive REPL
gen-model Scaffold a schema from an existing collection
test Run the test suite
Use gdmongolite --help for command-specific options.

11. Testing

Install development dependencies:

pip install gdmongolite[dev]
pytest --maxfail=1 --disable-warnings -q
  • Uses pytest-asyncio for async tests
  • Aim for ≥ 95% code coverage

12. Project Layout

gdmongolite/
├── src/gdmongolite/
│   ├── __init__.py
│   ├── core.py            # DB façade and connection logic
│   ├── schema.py          # Schema metaclass and built-in types
│   ├── query.py           # Filter parser and Cursor class
│   ├── migrate.py         # Migration engine
│   ├── telemetry.py       # Hook registry
│   ├── cli.py             # Click-based CLI commands
│   ├── config.py          # Pydantic BaseSettings
│   └── utils.py           # Internal helpers
├── migrations/            # Auto-generated migration scripts
├── tests/                 # Unit and integration tests
├── README.md
├── LICENSE
├── pyproject.toml
└── .env

13. Best Practices

  • Keep schemas focused: One schema per document type
  • Commit migrations: Ensure your database schema changes are versioned
  • Use telemetry: Capture performance and error metrics early
  • Test across modes: Run tests in both sync and async contexts
  • Leverage CLI: Automate repetitive tasks (shell, migrations, model generation)

14. FAQ

Q: How to handle large datasets? A: Use cursor batching:

cursor = db.User.find().batch_size(100)
for batch in await cursor.to_list():
    process(batch)

Q: Can I integrate with FastAPI? A: Yes. Initialize db in your startup event and import schemas into routers. Q: Are transactions supported? A: Use:

async with db.transaction():
    await db.Order.insert({...})
    await db.Inventory.update({...})

gdmongolite empowers everyone—from beginners to experts—to build MongoDB-backed applications with minimal boilerplate, robust validation, and comprehensive tooling. Start coding and let gdmongolite handle the rest

Author

Ganesh Datta Padamata Email: ganeshdattapadamata@gmail.com PyPI: ganeshdatta999

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

gdmongolite-0.1.2.tar.gz (6.0 kB view details)

Uploaded Source

Built Distribution

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

gdmongolite-0.1.2-py3-none-any.whl (8.3 kB view details)

Uploaded Python 3

File details

Details for the file gdmongolite-0.1.2.tar.gz.

File metadata

  • Download URL: gdmongolite-0.1.2.tar.gz
  • Upload date:
  • Size: 6.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.9

File hashes

Hashes for gdmongolite-0.1.2.tar.gz
Algorithm Hash digest
SHA256 c3c4e38d7b020ab25c52495ce89541c8af30b9ebc656eb68f34b21c861bcabb3
MD5 76c846baaa6025ba5ca826f2e7fe5390
BLAKE2b-256 256d34ade8790a66da4b370ec2ca0c74e07089beed2a590532934d31527d919f

See more details on using hashes here.

File details

Details for the file gdmongolite-0.1.2-py3-none-any.whl.

File metadata

  • Download URL: gdmongolite-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 8.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.9

File hashes

Hashes for gdmongolite-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 92564baa7d12d053f20ddb10519b42b6c965c51faf049ec9165d3cc15e082cca
MD5 d22b429874bf2307c5f25241386a5f8b
BLAKE2b-256 423b4b83943360e309606dbbc04180d28acde563dad49259c09883f0c8d28e91

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