## providers.mongodb.MongoDbDao

<span id="hexkit.providers.mongodb.MongoDbDao"></span>


A MongoDb-specific DAO.


Usage

``` python
providers.mongodb.MongoDbDao(
    *, dto_model, id_field, collection, document_to_dto, dto_to_document
)
```


## Methods

| Name | Description |
|----|----|
| [__init__()](#__init__) | Initialize the DAO. |
| [delete()](#delete) | Delete a resource by providing its ID. |
| [find_all()](#find_all) | Find all resources that match the specified mapping. |
| [find_one()](#find_one) | Find the resource that matches the specified mapping. |
| [get_by_id()](#get_by_id) | Get a resource by providing its ID. |
| [insert()](#insert) | Create a new resource. |
| [update()](#update) | Update an existing resource. |
| [upsert()](#upsert) | Update the provided resource if it already exists, create it otherwise. |
| [with_transaction()](#with_transaction) | Creates a transaction manager that uses an async context manager interface: |

<span id="__init__"></span>

<span id="hexkit.providers.mongodb.MongoDbDao.__init__"></span>


#### \_\_init\_\_()


Initialize the DAO.


Usage

``` python
__init__(*, dto_model, id_field, collection, document_to_dto, dto_to_document)
```


##### Parameters


`dto_model: type[Dto]`  
A DTO (Data Transfer Object) model describing the shape of resources.

`id_field: str`  
The name of the field of the `dto_model` that serves as resource ID. (DAO implementation might use this field as primary key.)

`collection: AsyncCollection`  
A collection object from the pymongo async library.

`document_to_dto: Callable[[dict[str, Any]], Dto]`  
A callable that takes a document obtained from the MongoDB database and returns a DTO model-compliant representation.

`dto_to_document: Callable[[Dto], dict[str, Any]]`  
A callable that takes a DTO model and returns a representation that is a compatible document for a MongoDB database.


<span id="hexkit.providers.mongodb.MongoDbDao.delete"></span>

------------------------------------------------------------------------


#### delete()


Delete a resource by providing its ID.


Usage

``` python
delete(id_)
```


##### Parameters


`id_: ID`  
The ID of the resource.


##### Raises


`ResourceNotFoundError`  
when resource with the specified id\_ was not found


<span id="hexkit.providers.mongodb.MongoDbDao.find_all"></span>

------------------------------------------------------------------------


#### find_all()


Find all resources that match the specified mapping.


Usage

``` python
find_all(*, mapping, skip=None, limit=None, sort=None)
```


The values in the mapping are used to filter the resources. Provide them using the same Python types as the corresponding DTO model fields; UUIDs and datetimes are stored and matched natively, so they must not be passed as strings. Dictionaries can be passed as values to specify more complex MongoDB queries.


##### Parameters


`mapping: Mapping[str, Any]`  
A mapping where the keys correspond to the names of resource fields and the values correspond to the actual values of the resource fields.

`skip: int | None = None`  
Number of matching resources to skip before yielding results. Defaults to None (no skipping).

`limit: int | None = None`  
Maximum number of resources to yield. Defaults to None (no limit). Specifying 0 is interpreted literally and returns no results.

`sort: list[str] | None = None`  
A list of field names defining the sort order, where field names prefixed with "-" indicate *descending* order. For example, if sort is specified as `["name", "-age"]`, the results would be sorted first by "name" in ascending order, then by "age" in descending order. When paginating with skip/limit, providing a sort order is strongly recommended to ensure consistent, deterministic results. Defaults to None (no sort).


##### Returns


`FindResult[Dto]`  
A FindResult that is async-iterable and also provides total_count().


<span id="hexkit.providers.mongodb.MongoDbDao.find_one"></span>

------------------------------------------------------------------------


#### find_one()


Find the resource that matches the specified mapping.


Usage

``` python
find_one(*, mapping)
```


It is expected that at most one resource matches the constraints. An exception is raised if no or multiple hits are found.

The values in the mapping are used to filter the resources. Provide them using the same Python types as the corresponding DTO model fields; UUIDs and datetimes are stored and matched natively, so they must not be passed as strings. Dictionaries can be passed as values to specify more complex MongoDB queries.


##### Parameters


`mapping: Mapping[str, Any]`  
A mapping where the keys correspond to the names of resource fields and the values correspond to the actual values of the resource fields


##### Returns


`Dto`  
Returns a hit in the form of the respective DTO model if exactly one hit

was found that matches the given mapping.


##### Raises


`NoHitsFoundError`  
If no hit was found.

`MultipleHitsFoundError`  
Raised when obtaining more than one hit.


<span id="hexkit.providers.mongodb.MongoDbDao.get_by_id"></span>

------------------------------------------------------------------------


#### get_by_id()


Get a resource by providing its ID.


Usage

``` python
get_by_id(id_)
```


##### Parameters


`id_: ID`  
The ID of the resource.


##### Returns


`Dto`  
The resource represented using the respective DTO model.


##### Raises


`ResourceNotFoundError`  
when resource with the specified id\_ was not found


<span id="hexkit.providers.mongodb.MongoDbDao.insert"></span>

------------------------------------------------------------------------


#### insert()


Create a new resource.


Usage

``` python
insert(dto)
```


##### Parameters


`dto: Dto`  
Resource content as a pydantic-based data transfer object including the resource ID.


##### Raises


`ResourceAlreadyExistsError`  
when a resource with the ID specified in the dto does already exist.

`UniqueConstraintViolationError`  
when inserting the dto would violate a unique index constraint over some field other than the ID field.


<span id="hexkit.providers.mongodb.MongoDbDao.update"></span>

------------------------------------------------------------------------


#### update()


Update an existing resource.


Usage

``` python
update(dto)
```


##### Parameters


`dto: Dto`  
The updated resource content as a pydantic-based data transfer object including the resource ID.


##### Raises


`ResourceNotFoundError`  
when resource with the id specified in the dto was not found

`UniqueConstraintViolationError`  
when updating the dto would violate a unique index constraint over some field other than the ID field.


<span id="hexkit.providers.mongodb.MongoDbDao.upsert"></span>

------------------------------------------------------------------------


#### upsert()


Update the provided resource if it already exists, create it otherwise.


Usage

``` python
upsert(dto)
```


##### Parameters


`dto: Dto`  
Resource content as a pydantic-based data transfer object including the resource ID.


##### Raises


`UniqueConstraintViolationError`  
when upserting the dto would violate a unique index constraint over some field other than the ID field.


<span id="hexkit.providers.mongodb.MongoDbDao.with_transaction"></span>

------------------------------------------------------------------------


#### with_transaction()


Creates a transaction manager that uses an async context manager interface:


Usage

``` python
with_transaction()
```


Upon **aenter**, pens a new transactional scope. Returns a transaction-scoped DAO.

Upon **aexit**, closes the transactional scope. A full rollback of the transaction is performed in case of an exception. Otherwise, the changes to the database are committed and flushed.
