Mongodb
the_data_packet.utils.mongodb
¶
logger = get_logger(__name__)
module-attribute
¶
MongoDBClient
¶
A MongoDB client wrapper for database operations.
This class provides a simplified interface for connecting to MongoDB and performing common database operations like inserting and querying documents.
Attributes:
| Name | Type | Description |
|---|---|---|
client |
MongoClient
|
The MongoDB client instance. |
db |
Database
|
The MongoDB database instance. |
client: MongoClient = MongoClient(connection_string, serverSelectionTimeoutMS=5000)
instance-attribute
¶
db: Database = self.client.the_data_packet
instance-attribute
¶
__init__(username: str, password: str) -> None
¶
Initialize the MongoDB client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
username
|
str
|
The username for MongoDB authentication. |
required |
password
|
str
|
The password for MongoDB authentication. |
required |
get_collection(collection_name: str) -> Collection
¶
Get a collection from the database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
collection_name
|
str
|
The name of the collection to retrieve. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Collection |
Collection
|
The MongoDB collection instance. |
insert_document(collection_name: str, document: Dict[str, Any]) -> InsertOneResult
¶
Insert a single document into a collection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
collection_name
|
str
|
The name of the collection to insert into. |
required |
document
|
Dict[str, Any]
|
The document to insert. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
InsertOneResult |
InsertOneResult
|
The result of the insert operation, containing information about the insertion including the inserted_id. |
find_documents(collection_name: str, query: Optional[Dict[str, Any]] = None) -> Cursor
¶
Find documents in a collection based on a query.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
collection_name
|
str
|
The name of the collection to search in. |
required |
query
|
Optional[Dict[str, Any]]
|
The query filter. If None or empty, returns all documents in the collection. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Cursor |
Cursor
|
A cursor object that can be iterated over to access the matching documents. |
close() -> None
¶
Close the MongoDB client connection.
This should be called when the client is no longer needed to properly close the connection and free resources.