Skip to main content

Pydantic Async Mongo Document

Project description

Pydantic Mongo Document

pydantic_mongo_document is a Python library that combines the power of Pydantic models with MongoDB, providing an elegant way to work with MongoDB documents using Python type hints and data validation.

Features

  • Full Pydantic integration with MongoDB documents
  • Support for both synchronous and asynchronous operations
  • Type-safe document models with validation
  • Built-in ObjectId handling and JSON encoding
  • Flexible MongoDB replica configuration
  • Rich query interface with type hints
  • Automatic index management
  • Support for MongoDB transactions

Installation

Install the package using pip or poetry.

# Using pip
pip install pydantic_mongo_document

# Using poetry
poetry add pydantic_mongo_document

Basic Usage

Configuration

First, configure your MongoDB connection:

from pydantic_mongo_document import Document

# Basic configuration
Document.set_replica_config({
    "localhost": {
        "uri": "mongodb://localhost:27017",
        "client_options": {
            "replica_set": "rs0",  # optional
            "max_pool_size": 100,
            "write_concern": "majority",
            "read_preference": "primaryPreferred"
        }
    }
})

Define Your Models

Create document models by inheriting from either sync or async Document classes:

from pydantic_mongo_document.document.asyncio import Document as AsyncDocument
from pydantic_mongo_document.document.sync import Document as SyncDocument

# Async Document
class AsyncUser(AsyncDocument):
    __replica__ = "localhost"
    __database__ = "myapp"
    __collection__ = "users"

    name: str
    email: str
    age: int | None = None

# Sync Document
class User(SyncDocument):
    __replica__ = "localhost"
    __database__ = "myapp"
    __collection__ = "users"

    name: str
    email: str
    age: int | None = None

Async Usage Example

async def user_crud_example():
    # Create a new user
    user = AsyncUser(name="John Doe", email="john@example.com")
    await user.insert()

    # Find a user
    user = await AsyncUser.one(add_query={"email": "john@example.com"})
    
    # Update user
    user.age = 30
    await user.commit_changes()

    # Delete user
    await user.delete()

    # Query multiple users
    async for user in AsyncUser.all(add_query={"age": {"$gt": 25}}):
        print(user)

    # Count users
    count = await AsyncUser.count(add_query={"age": {"$gt": 25}})

Sync Usage Example

# Create a new user
user = User(name="Jane Doe", email="jane@example.com")
user.insert()

# Find a user
user = User.one(add_query={"email": "jane@example.com"})

# Update user
user.age = 28
user.commit_changes()

# Query multiple users
for user in User.all(add_query={"age": {"$gt": 25}}):
    print(user)

# Count users
count = User.count(add_query={"age": {"$gt": 25}})

Advanced Features

Working with MongoDB Transactions

async def transaction_example():
    async with await AsyncUser.client().start_session() as session:
        async with session.start_transaction():
            user = AsyncUser(name="John", email="john@example.com")
            await user.insert(session=session)
            # Transaction will automatically commit if no exceptions occur
            # or rollback if an exception is raised

Custom Indexes

class User(AsyncDocument):
    __replica__ = "localhost"
    __database__ = "myapp"
    __collection__ = "users"

    name: str
    email: str

    @classmethod
    async def create_indexes(cls):
        # Create custom indexes
        await cls.collection().create_index("email", unique=True)
        await cls.collection().create_index([("name", 1), ("email", 1)])
        return await super().create_indexes()

Advanced Queries

# Find with projection
user = await User.one(
    add_query={"age": {"$gt": 25}},
    projection={"name": 1, "email": 1}
)

# Complex queries
users = User.all(add_query={
    "age": {"$gt": 25},
    "email": {"$regex": "@example\.com$"},
    "$or": [
        {"name": {"$regex": "^John"}},
        {"name": {"$regex": "^Jane"}}
    ]
})

Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

MIT License

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

pydantic_mongo_document-2.0.5.tar.gz (10.7 kB view details)

Uploaded Source

Built Distribution

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

pydantic_mongo_document-2.0.5-py3-none-any.whl (12.9 kB view details)

Uploaded Python 3

File details

Details for the file pydantic_mongo_document-2.0.5.tar.gz.

File metadata

  • Download URL: pydantic_mongo_document-2.0.5.tar.gz
  • Upload date:
  • Size: 10.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.5 CPython/3.11.1 Darwin/24.3.0

File hashes

Hashes for pydantic_mongo_document-2.0.5.tar.gz
Algorithm Hash digest
SHA256 e084a8fdfbdab42db4b78ff7101b00532ca5bd8ac9d634cfc4964bc1211a8e66
MD5 bc1cea2e9432391b88753b824122e23b
BLAKE2b-256 35f373d282ef5fa2691dec2e3e42612d9c07af46be9300976dddad91e0d76b7d

See more details on using hashes here.

File details

Details for the file pydantic_mongo_document-2.0.5-py3-none-any.whl.

File metadata

File hashes

Hashes for pydantic_mongo_document-2.0.5-py3-none-any.whl
Algorithm Hash digest
SHA256 173bf28ee7761b6b84b2b312b0f538d1dcaf7e11949ec363c00db3d3aa5a3c30
MD5 57294b578c6a2876ed6926287e1bde9f
BLAKE2b-256 c8c52e084eb98fb5a69aea17efa2337ab0dc5cee6110b31ba132e895c26b3ebb

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