Created
December 9, 2021 23:13
-
-
Save samdev-7/2d42b241369776f6109b08000d2804d6 to your computer and use it in GitHub Desktop.
db = MongoDB('CONNECTION_STRING', database='mydb', collection='mycollection') #Use as Python dictionary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pymongo import MongoClient | |
class MongoDB(): | |
def __init__(self, connectionString, database, collection): | |
self._client = MongoClient(connectionString) | |
self._db = self._client[database] | |
self._col = self._db[collection] | |
def __setitem__(self, key, value): | |
self._col.update_one({'_id': key}, {"$set": {'_id': key, 'value': value}}, upsert=True) | |
def __getitem__(self, key): | |
result = self._col.find_one({'_id': key}) | |
if not result: | |
raise KeyError(key) | |
else: | |
return result['value'] | |
def __delitem__(self, key): | |
result = self._col.delete_one({'_id': key}) | |
if result.deleted_count == 0: | |
raise KeyError(key) | |
def __len__(self): | |
return self._col.count_documents({}) | |
def __iter__(self): | |
return (item['_id'] for item in self._col.find({})) | |
def __contains__(self, key): | |
result = self._col.find_one({'_id': key}) | |
if not result: | |
return False | |
else: | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment