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 bson import ObjectId
from pydantic import BaseModel
from pydantic_mongo import AbstractRepository, ObjectIdField
from pymongo import MongoClient
from typing import List
import os
class Foo(BaseModel):
count: int
size: float = None
class Bar(BaseModel):
apple: str = 'x'
banana: str = 'y'
class Spam(BaseModel):
id: ObjectIdField = None
foo: Foo
bars: List[Bar]
class SpamRepository(AbstractRepository[Spam]):
class Meta:
collection_name = 'spams'
client = MongoClient("mongodb://localhost:27017")
database = client["example"]
spam = Spam(foo=Foo(count=1, size=1.0),bars=[Bar()])
spam_with_predefined_id = Spam(
id=ObjectId("611827f2878b88b49ebb69fc"),
foo=Foo(count=2, size=2.0),
bars=[Bar()]
)
spam_repository = SpamRepository(database=database)
# Insert / Update
spam_repository.save(spam)
# Insert / Update many items
spam_repository.save_many([spam, spam_with_predefined_id])
# 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'))
assert result.foo.count == 2
# 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=list(edges)[-1].cursor)
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.1.1.tar.gz
(9.6 kB
view hashes)
Built Distribution
Close
Hashes for pydantic_mongo-2.1.1-py2.py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 8f5fdf42a82dd91c73732966c2e053f6b783faae761f1a4154297224af2f773d |
|
MD5 | 9bb0408cef96eacd1da6c921ddf02cb5 |
|
BLAKE2b-256 | 30e45d816a7c44772fe2632ccfe551248505d844142013192551131b5d3fa0aa |