36 lines
1.2 KiB
Python
36 lines
1.2 KiB
Python
"""import logging
|
|
from pymongo import MongoClient
|
|
|
|
from app.repositories.abc import IDocumentStore
|
|
|
|
|
|
class MongoDB(IDocumentStore):
|
|
|
|
def __init__(self, client: MongoClient):
|
|
self._client = client
|
|
self._logger = logging.getLogger(__name__)
|
|
|
|
def save_to_db(self, collection: str, item):
|
|
collection_ref = self._client[collection]
|
|
result = collection_ref.insert_one(item)
|
|
if result.inserted_id:
|
|
self._logger.info(f"Document added with ID: {result.inserted_id}")
|
|
return True, str(result.inserted_id)
|
|
else:
|
|
return False, None
|
|
|
|
def save_to_db_with_id(self, collection: str, item, doc_id: str):
|
|
collection_ref = self._client[collection]
|
|
item['_id'] = doc_id
|
|
result = collection_ref.replace_one({'_id': id}, item, upsert=True)
|
|
if result.upserted_id or result.matched_count:
|
|
self._logger.info(f"Document added with ID: {doc_id}")
|
|
return True, doc_id
|
|
else:
|
|
return False, None
|
|
|
|
def get_all(self, collection: str):
|
|
collection_ref = self._client[collection]
|
|
all_documents = list(collection_ref.find())
|
|
return all_documents
|
|
""" |