API Reference
Mongo Class
Provides an interface to MongoDB with support for SSH tunneling and LDAP authentication.
Class Attributes
timeout
(int): Connection timeout in millisecondsserver
(SSHTunnelForwarder): SSH tunnel connection if activeusername
(str): Current username for authenticationdbClient
(MongoClient): MongoDB client connectiondb
(Database): Current active databasefs
(GridFS): GridFS instance for file operationsdbList
(List[str]): List of available databasescollList
(List[str]): List of collections in current database
Constructor
def __init__(
self,
host: str,
port: int = 27017,
authentication: Optional[str] = None,
username: Optional[str] = None,
password: Optional[str] = None,
ssh: bool = False,
ssh_host: Optional[str] = None,
database: Optional[str] = None,
ssh_username: Optional[str] = None,
ssh_password: Optional[str] = None,
timeout: int = 5000,
):
Establishes connection to a MongoDB server based on provided parameters.
Connection Methods
_connect_directly
def _connect_directly(self, uri: str) -> None:
_connect_via_ssh
def _connect_via_ssh(
self,
host: str,
port: int,
ssh_host: str,
ssh_username: Optional[str],
ssh_password: Optional[str],
database: Optional[str],
username: str,
password: str,
) -> None:
_connect_with_ldap
def _connect_with_ldap(
self,
host: Union[str, List[str]],
port: int,
password: Optional[str]
) -> None:
Database Operations
getDBs
def getDBs(self) -> List[str]:
setDB
def setDB(self, db_name: str) -> None:
Record Operations
getRecord
def getRecord(
self,
collection: str,
field: Union[str, ObjectId, Dict]
) -> Dict:
getRecords
def getRecords(self, collection: str) -> List[Dict]:
newRecord
def newRecord(self, collection: str, **kwargs) -> ObjectId:
updateRecord
def updateRecord(
self,
collection: str,
field: Union[str, ObjectId, Dict],
updateVals: Dict,
updateType: str
) -> None:
deleteRecords
def deleteRecords(self, collection: str) -> None:
dropCollection
def dropCollection(self, collection: str) -> None:
File Operations (GridFS)
putFile
def putFile(self, filepath: str, **kwargs) -> ObjectId:
getFile
def getFile(self, fileID: Union[str, ObjectId]) -> bytes:
deleteFile
def deleteFile(self, fileID: Union[str, ObjectId]) -> None:
Helper Methods
_validate_field
def _validate_field(
self,
field: Union[str, ObjectId, Dict]
) -> Dict:
Exceptions
ValueError
: Raised for invalid database names, collection names, or update typesTypeError
: Raised for invalid field types or parameterspymongo.errors.ServerSelectionTimeoutError
: Raised for connection timeoutsException
: Generic exceptions with descriptive messages
Type Hints
The package uses the following type hints:
from typing import Dict, List, Optional, Union
from bson.objectid import ObjectId
from sshtunnel import SSHTunnelForwarder
from pymongo.database import Database
from gridfs import GridFS