Skip to main content

Document object mapper for pydantic and pymongo

Project description

Build Status Maintainability Test Coverage Version Pyversions

Document object mapper for pydantic and pymongo

Documentation

Usage

Install:

$ pip install pydantic-mongo

from pydantic import BaseModel
from pydantic_mongo import AbstractRepository, ObjectIdField
from pymongo import MongoClient

class Foo(BaseModel):
    count: int
    size: float = None

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

class Spam(BaseModel):
    id: ObjectIdField = None
    foo: Foo
    bars: List[Bar]

    class Config:
        # The ObjectIdField creates an bson ObjectId value, so its necessary to setup the json encoding
        json_encoders = {ObjectId: str}

class SpamRepository(AbstractRepository[Spam]):
    class Meta:
        collection_name = 'spams'

client = MongoClient(os.environ["MONGODB_URL"])
database = client[os.environ["MONGODB_DATABASE"]]

spam = Spam(foo=Foo(count=1, size=1.0),bars=[Bar()])

spam_repository = SpamRepository(database=database)

# Insert / Update
spam_repository.save(spam)

# Delete
spam_repository.delete(spam)

# Find One By Id
result = spam_repository.find_one_by_id(spam.id)

# Find One By Query
result = spam_repository.find_one_by({'foo.count': 1})

# Find By Query
results = spam_repository.find_by({'foo.count': {'$gte': 1}})

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-0.1.2.tar.gz (7.1 kB view hashes)

Uploaded Source

Built Distribution

pydantic_mongo-0.1.2-py2.py3-none-any.whl (6.6 kB view hashes)

Uploaded Python 2 Python 3

Supported by

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