Skip to main content

Pydantic Mongo

Build Status Maintainability Test Coverage Version Downloads Documentation Status

A Python library that offers an easy-to-use Repository pattern for MongoDB, supporting both synchronous and asynchronous operations. It simplifies working with databases by providing a clear interface for CRUD (Create, Read, Update, Delete) operations using Pydantic models. With built-in data validation and serialization from Pydantic, it helps manage your MongoDB data safely.

Read the documentation

Features

  • Asynchronous and Synchronous support
  • Pydantic models integration
  • Type-safe MongoDB operations
  • Cursor-based pagination

Installation

pip install pydantic-mongo

Usage Examples

Defining Models and Repository

from bson import ObjectId
from pydantic import BaseModel
from pydantic_mongo import AbstractRepository, PydanticObjectId
from pymongo import MongoClient
from typing import Optional, List

# Define your models
class Foo(BaseModel):
   count: int
   size: float = None

class Bar(BaseModel):
   apple: str = 'x'
   banana: str = 'y'

class Spam(BaseModel):
   # PydanticObjectId is an alias to Annotated[ObjectId, ObjectIdAnnotation]
   id: Optional[PydanticObjectId] = None
   foo: Foo
   bars: List[Bar]

# Create a repository
class SpamRepository(AbstractRepository[Spam]):
   class Meta:
      collection_name = 'spams'

# Connect to database
client = MongoClient("mongodb://localhost:27017")
database = client["example"]
repo = SpamRepository(database)

Creating and Saving Documents

# Create a new document
spam = Spam(foo=Foo(count=1, size=1.0), bars=[Bar()])

# Create a document with predefined ID
spam_with_predefined_id = Spam(
   id=ObjectId("611827f2878b88b49ebb69fc"),
   foo=Foo(count=2, size=2.0),
   bars=[Bar()]
)

# Save a single document
repo.save(spam)  # spam.id is now set to an ObjectId

# Save multiple documents
repo.save_many([spam, spam_with_predefined_id])

Querying Documents

# Find by ID
result = repo.find_one_by_id(spam.id)

# Find by ID using string
result = repo.find_one_by_id(ObjectId('611827f2878b88b49ebb69fc'))
assert result.foo.count == 2

# Find one by custom query
result = repo.find_one_by({'foo.count': 1})

# Find multiple documents by query
results = repo.find_by({'foo.count': {'$gte': 1}})

Pagination

# Get first page
edges = repo.paginate({'foo.count': {'$gte': 1}}, limit=10)

# Get next page using the last cursor
more_edges = repo.paginate(
    {'foo.count': {'$gte': 1}}, 
    limit=10, 
    after=list(edges)[-1].cursor
)

Deleting Documents

# Delete a document
repo.delete(spam)

# Delete by ID
repo.delete_by_id(ObjectId("..."))

Async Support

For asynchronous applications, you can use AsyncAbstractRepository which provides the same functionality as AbstractRepository but with async/await support:

from pymongo import AsyncMongoClient
from pydantic import BaseModel
from pydantic_mongo import AsyncAbstractRepository

class User(BaseModel):
    id: str
    name: str
    email: str

class UserRepository(AsyncAbstractRepository[User]):
    class Meta:
        collection_name = 'users'

# Initialize database connection
client = AsyncMongoClient('mongodb://localhost:27017')
database = client["mydb"]

# Create repository instance
user_repo = UserRepository(database)

# Example usage
user = User(name='John Doe', email='john@example.com')
await user_repo.save(user)

user = await user_repo.find_one_by_id(user_id)

License

MIT License

Metadata

Release files for pydantic-mongo 3.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pydantic-mongo 3.1.0
File Size Uploaded Provenance Actions
pydantic_mongo-3.1.0.tar.gz 14.8 kB Without provenance Details for pydantic_mongo-3.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pydantic-mongo 3.1.0
File Interpreter ABI Platform Actions
pydantic_mongo-3.1.0-py2.py3-none-any.whl Python 3, Python 2 none any Details for pydantic_mongo-3.1.0-py2.py3-none-any.whl

Total release size: 29.3 kB

Release files / pydantic_mongo-3.1.0.tar.gz

Download URL pydantic_mongo-3.1.0.tar.gz
Size 14.8 kB
Tags Source
SHA-256 checksum
How to use checksums
e29851c893d572d26d99b5cdd83282ac0d40439829357ad45bdb4d4477120eae
BLAKE2b-256 checksum
How to use checksums
ef03b65f84f0d71164a873ec3e1a7ea1d0db8934b9b81463c8d6196f93d8c722
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.12.9

Release files / pydantic_mongo-3.1.0-py2.py3-none-any.whl

Download URL pydantic_mongo-3.1.0-py2.py3-none-any.whl
Size 14.5 kB
Tags Python 2 Python 3
SHA-256 checksum
How to use checksums
e94eaff4a73ad1d6cbcb617ed618fca1a31b870ea82d765736bf0c0774ac68d7
BLAKE2b-256 checksum
How to use checksums
926e3d03197ea58bb5d05324b1781d9d1a1ffe54b0999f1178a09edb611969c0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.12.9

Security for pydantic-mongo 3.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page