Document object mapper for pydantic and pymongo
Project description
Pydantic Mongo
Document object mapper for pydantic and pymongo
Usage
Install:
pip install pydantic-mongo
Example Code
from pydantic import BaseModel
from pydantic_mongo import AbstractRepository, ObjectIdField
from pymongo import MongoClient
from bson import ObjectId
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 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)
# Insert / Update many items
spam_repository.save_many([spam])
# Delete
spam_repository.delete(spam)
# Find One By Id
result = spam_repository.find_one_by_id(spam.id)
# Find One By Id using string if the id attribute is a ObjectIdField
result = spam_repository.find_one_by_id(ObjectId('611827f2878b88b49ebb69fc'))
# 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}})
# Paginate using cursor based pagination
edges = spam_repository.paginate({'foo.count': {'$gte': 1}}, limit=1)
more_edges = spam_repository.paginate({'foo.count': {'$gte': 1}}, limit=1, after=edges[-1].cursor)
last_model = more_edges[-1].node
Project details
Release history Release notifications | RSS feed
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-2.0.2.tar.gz
(8.9 kB
view hashes)
Built Distribution
Close
Hashes for pydantic_mongo-2.0.2-py2.py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | a7a744941bbc29c9a3e181724c5a74f7fc4c01f0ea7e917678faa347a765f501 |
|
MD5 | 0fa2ae76e6d8614438ad35736e2e8835 |
|
BLAKE2b-256 | 177d1580ff92e159d63555de611488353e105185c87575460aa351837a1da158 |