### Uvicorn Server Output Example Source: https://art049.github.io/odmantic/usage_fastapi Example output indicating that the Uvicorn server has started and is serving the application. ```text INFO: Started server process [21429] INFO: Waiting for application startup. INFO: Application startup complete. INFO: Uvicorn running on http://localhost:8080 (Press CTRL+C to quit) ``` -------------------------------- ### Use Transaction with Raw Usage Source: https://art049.github.io/odmantic/api_reference/session Example demonstrating the raw usage of a transaction by manually starting, committing, and managing it. This approach requires explicit calls to `start()` and `commit()`. ```python engine = AIOEngine(...) transaction = engine.transaction() await transaction.start() john = await transaction.find(User, User.name == "John") john.name = "Doe" await transaction.save(john) await transaction.commit() ``` -------------------------------- ### start Source: https://art049.github.io/odmantic/api_reference/session Starts the logical session. Raises a RuntimeError if the session has already been started. ```APIDOC ## `start()` ### Description Start the logical session. ### Method ```python def start(self) -> None: """Start the logical session.""" if self.is_started: raise RuntimeError("Session is already started") self.session = self.engine.client.start_session() ``` ``` -------------------------------- ### Install FastAPI and Uvicorn Source: https://art049.github.io/odmantic/usage_fastapi Install the necessary libraries for running a FastAPI application. ```bash pip install fastapi uvicorn ``` -------------------------------- ### Install tox using pipx Source: https://art049.github.io/odmantic/contributing Install tox, a multi-environment test runner, using pipx. ```bash pipx install tox ``` -------------------------------- ### Install flit using pipx Source: https://art049.github.io/odmantic/contributing Install flit, a packaging system and dependency manager, using pipx. ```bash pipx install flit ``` -------------------------------- ### Configure Local Development Environment Source: https://art049.github.io/odmantic/contributing Run the 'task setup' command to configure the local development environment. ```bash task setup ``` -------------------------------- ### start() Source: https://art049.github.io/odmantic/api_reference/session Saves provided instances to the database. The operation modifies instances in place and returns them for convenience. ```APIDOC ## `start()` `async` ### Description Saves provided instances to the database. The operation modifies instances in place and returns them for convenience. ### Parameters * `instances`: The instances to save. ### Returns * A list of saved instances. ``` -------------------------------- ### Install pre-commit using pipx Source: https://art049.github.io/odmantic/contributing Install pre-commit, a pre-commit hook manager, using pipx. ```bash pipx install pre-commit ``` -------------------------------- ### start() Source: https://art049.github.io/odmantic/api_reference/session Starts the logical MongoDB session. This method should be called before performing any database operations within the session. It initializes the underlying Motor session. ```APIDOC ## start() ### Description Start the logical Mongo session. ### Method `async def start(self) -> None` ### Raises - `RuntimeError`: If the session is already started. ``` -------------------------------- ### Start MongoDB with Docker Source: https://art049.github.io/odmantic Use this command to start a local MongoDB instance using Docker. Closing the terminal will terminate the instance and remove the container. ```bash docker run --rm -p 27017:27017 mongo ``` -------------------------------- ### Support 'examples' Property in Field Descriptors Source: https://art049.github.io/odmantic/changelog Adds support for the `examples` property within Field descriptors. ```python Support the `examples` property in Field descriptors ``` -------------------------------- ### Example Usage of SyncEngine Transaction with Raw API Source: https://art049.github.io/odmantic/api_reference/session Illustrates the raw usage of `SyncEngine.transaction` by manually starting, committing, and saving operations. This approach requires explicit control over the transaction lifecycle. MongoDB transactions are only supported on replicated clusters. ```python engine = SyncEngine(...) transaction = engine.transaction() transaction.start() john = transaction.find(User, User.name == "John") john.name = "Doe" transaction.save(john) transaction.commit() ``` -------------------------------- ### Install ODMantic Source: https://art049.github.io/odmantic Install the ODMantic library using pip. Ensure you have Python 3.8+ and MongoDB 4.0+. ```bash pip install odmantic ``` -------------------------------- ### Create and use an ODMantic session with raw start/end calls Source: https://art049.github.io/odmantic/api_reference/session Manually start and end the session using `start()` and `end()` methods. Ensure `end()` is called to clean up resources. ```python engine = AIOEngine(...) session = engine.session() await session.start() john = await session.find(User, User.name == "John") john.name = "Doe" await session.save(john) await session.end() ``` -------------------------------- ### HTTPie Request to Get Tree by ID Source: https://art049.github.io/odmantic/usage_fastapi Example of how to use HTTPie to send a GET request to a FastAPI endpoint to retrieve a tree by its specific ObjectId. Demonstrates a successful retrieval. ```bash http localhost:8080/trees/5f8c8266f1d33aa1012f3082 ``` -------------------------------- ### Start a Transaction Source: https://art049.github.io/odmantic/api_reference/session Initiates a new transaction. Raises a RuntimeError if a transaction has already been started. If no session was provided, it starts one. ```python async def start(self) -> None: """Initiate the transaction.""" if self._transaction_started: raise RuntimeError("Transaction already started") if not self._session_provided: await self.session.start() assert self.session.session is not None self._transaction_context = ( await self.session.session.start_transaction().__aenter__() ) self._transaction_started = True ``` -------------------------------- ### Start Logical Session Source: https://art049.github.io/odmantic/api_reference/session Initiates a new logical session using the ODMantic engine's client. Raises a RuntimeError if the session is already started. ```python def start(self) -> None: """Start the logical session.""" if self.is_started: raise RuntimeError("Session is already started") self.session = self.engine.client.start_session() ``` -------------------------------- ### Initialize ODMantic Engine Source: https://art049.github.io/odmantic/api_reference/engine Instantiate the AIOEngine. If no client is provided, a default AsyncIOMotorClient will be created. Requires the 'motor' package to be installed. ```python def __init__( self, client: Union["AsyncIOMotorClient", None] = None, database: str = "test", ): """Engine constructor. Args: client: instance of an AsyncIO motor client. If None, a default one will be created database: name of the database to use """ if not motor: raise RuntimeError( "motor is required to use AIOEngine, install it with:\n\n" + 'pip install "odmantic[motor]"' ) if client is None: client = AsyncIOMotorClient() super().__init__(client=client, database=database) ``` -------------------------------- ### Install pipx for Python Development Tools Source: https://art049.github.io/odmantic/contributing Use pipx to install Python-based development tools. Ensure pipx is added to your PATH. ```bash python3 -m pip install --user pipx python3 -m pipx ensurepath ``` -------------------------------- ### Start Transaction Source: https://art049.github.io/odmantic/api_reference/session Initiates a new transaction. Raises a RuntimeError if a transaction has already been started. ```python def start(self) -> None: """Initiate the transaction.""" if self._transaction_started: raise RuntimeError("Transaction already started") if not self._session_provided: self.session.start() assert self.session.session is not None self._transaction_context = self.session.session.start_transaction().__enter__() self._transaction_started = True ``` -------------------------------- ### Run FastAPI Application with Uvicorn Source: https://art049.github.io/odmantic/usage_fastapi Start the FastAPI application locally using the uvicorn server. ```bash uvicorn tree_api:app ``` -------------------------------- ### Session Start Transaction Source: https://art049.github.io/odmantic/api_reference/session Initiates a new transaction for the current session. If the session is not yet started, it will be started automatically. ```APIDOC ## start() async ### Description Initiate the transaction. ### Method `async def start(self) -> None:` ### Raises - `RuntimeError`: If the transaction has already been started. ### Notes This method manages the underlying session's transaction lifecycle. If the session itself hasn't been started, it will be initiated before starting the transaction. ``` -------------------------------- ### Install Python Versions with pyenv Source: https://art049.github.io/odmantic/contributing Install and manage multiple Python versions locally using pyenv. This is useful for testing the project against different Python environments. ```bash # Install the versions pyenv install "3.7.9" pyenv install "3.8.9" pyenv install "3.9.0" # Make the versions available locally in the project pyenv local 3.8.6 3.7.9 3.9.0 ``` -------------------------------- ### SyncEngine.session() Source: https://art049.github.io/odmantic/api_reference/engine Get a new session for the engine to allow ordering sequential operations. ```APIDOC ## SyncEngine.session() ### Description Get a new session for the engine to allow ordering sequential operations. ### Returns - a new session object ### Example usage: ```python engine = SyncEngine(...) with engine.session() as session: john = session.find(User, User.name == "John") john.name = "Doe" session.save(john) ``` ``` -------------------------------- ### Start an ODMantic session Source: https://art049.github.io/odmantic/api_reference/session Initiates a new logical Mongo session. Raises a RuntimeError if the session is already started. ```python async def start(self) -> None: """Start the logical Mongo session.""" if self.is_started: raise RuntimeError("Session is already started") self.session = await self.engine.client.start_session() ``` -------------------------------- ### Install ODMantic v1 Source: https://art049.github.io/odmantic/migration_guide Use pip to upgrade ODMantic to the latest version. ```bash pip install -U pydantic ``` -------------------------------- ### Create Tree using HTTPie Source: https://art049.github.io/odmantic/usage_fastapi Example of creating a new tree resource from the command line using HTTPie. This sends a PUT request with JSON data. ```bash http PUT localhost:8080/trees/ name="Spruce" discovery_year=1995 average_size=2 ``` -------------------------------- ### Get trees using HTTPie Source: https://art049.github.io/odmantic/usage_fastapi Retrieves all 'Tree' instances from the database using HTTPie. This command fetches the list of trees. ```bash http localhost:8080/trees/ ``` -------------------------------- ### FastAPI Tree API Example Source: https://art049.github.io/odmantic/usage_fastapi A complete FastAPI application demonstrating CRUD operations for a Tree model using odmantic and AIOEngine. ```python from typing import List from fastapi import FastAPI, HTTPException from odmantic import AIOEngine, Model, ObjectId class Tree(Model): name: str average_size: float discovery_year: int app = FastAPI() engine = AIOEngine() @app.put("/trees/", response_model=Tree) async def create_tree(tree: Tree): await engine.save(tree) return tree @app.get("/trees/", response_model=List[Tree]) async def get_trees(): trees = await engine.find(Tree) return trees @app.get("/trees/count", response_model=int) async def count_trees(): count = await engine.count(Tree) return count @app.get("/trees/{id}", response_model=Tree) async def get_tree_by_id(id: ObjectId): tree = await engine.find_one(Tree, Tree.id == id) if tree is None: raise HTTPException(404) return tree ``` -------------------------------- ### Create Tree using curl Source: https://art049.github.io/odmantic/usage_fastapi Example of creating a new tree resource from the command line using curl. This sends a PUT request with a JSON payload. ```bash curl -X PUT "http://localhost:8080/trees/" \ -H "Content-Type: application/json" \ -d '{"name":"Spruce", "discovery_year":1995, "average_size":2}' ``` -------------------------------- ### Create and use an ODMantic session as a context manager Source: https://art049.github.io/odmantic/api_reference/session Use the session as an asynchronous context manager to ensure it is properly started and ended. This is the recommended way to use sessions. ```python engine = AIOEngine(...) async with engine.session() as session: john = await session.find(User, User.name == "John") john.name = "Doe" await session.save(john) ``` -------------------------------- ### Initialize AIOEngine Source: https://art049.github.io/odmantic/api_reference/engine Constructs an AIOEngine instance for asynchronous MongoDB operations. If no client is provided, a default one is created. Requires the 'motor' library to be installed. ```python client: "AsyncIOMotorClient" database: "AsyncIOMotorDatabase" def __init__( self, client: Union["AsyncIOMotorClient", None] = None, database: str = "test", ): """Engine constructor. Args: client: instance of an AsyncIO motor client. If None, a default one will be created database: name of the database to use <--- #noqa: DAR401 RuntimeError --> """ if not motor: raise RuntimeError( "motor is required to use AIOEngine, install it with: " + 'pip install "odmantic[motor]"' ) if client is None: client = AsyncIOMotorClient() super().__init__(client=client, database=database) ``` -------------------------------- ### SyncSession Raw Usage Source: https://art049.github.io/odmantic/api_reference/session Illustrates manual control over the SyncSession lifecycle, including explicitly starting and ending the session. This is useful for more granular control over session operations. ```python engine = SyncEngine(...) session = engine.session() session.start() john = session.find(User, User.name == "John") john.name = "Doe" session.save(john) session.end() ``` -------------------------------- ### HTTPie Request for Non-existent Tree Source: https://art049.github.io/odmantic/usage_fastapi Example using HTTPie to request a tree with an ID that does not exist in the database. This demonstrates the expected 404 Not Found response. ```bash http localhost:8080/trees/f0f0f0f0f0f0f0f0f0f0f0f0 ``` -------------------------------- ### Configure Database with Product Model (Async) Source: https://art049.github.io/odmantic/modeling Initialize an AIOEngine and call configure_database to create and enable indexes for the specified models. This asynchronous method should be awaited. ```python # ... Continuation of the previous snippet ... from odmantic import AIOEngine engine = AIOEngine() await engine.configure_database([Product]) ``` -------------------------------- ### Synchronous Transaction with Abort Source: https://art049.github.io/odmantic/engine Use `engine.transaction()` to start a synchronous transaction. Operations within the `with` block can be discarded by calling `transaction.abort()` before the block exits. ```python from odmantic import Model, SyncEngine class Player(Model): name: str game: str engine = SyncEngine() with engine.transaction() as transaction: transaction.save(Player(name="Shroud", game="Counter-Strike")) transaction.save(Player(name="Serral", game="Starcraft")) transaction.abort() print(engine.count(Player)) ``` -------------------------------- ### Curl Request to Get Tree by ID Source: https://art049.github.io/odmantic/usage_fastapi Example of how to use curl to send a GET request to a FastAPI endpoint to retrieve a tree by its specific ObjectId. Demonstrates a successful retrieval. ```bash curl http://localhost:8080/trees/5f8c8266f1d33aa1012f3082 ``` -------------------------------- ### Configure Database with Product Model (Sync) Source: https://art049.github.io/odmantic/modeling Initialize a SyncEngine and call configure_database to create and enable indexes for the specified models. This is the synchronous version for database configuration. ```python # ... Continuation of the previous snippet ... from odmantic import SyncEngine engine = SyncEngine() engine.configure_database([Product]) ``` -------------------------------- ### Get Underlying PyMongo Session Source: https://art049.github.io/odmantic/api_reference/session Retrieves the active PyMongo ClientSession. Raises a RuntimeError if the session has not been started. ```python def get_driver_session(self) -> ClientSession: """Return the underlying PyMongo Session""" if self.session is None: raise RuntimeError("session not started") return self.session ``` -------------------------------- ### Get Driver Session in ODMantic Source: https://art049.github.io/odmantic/api_reference/session Return the underlying Motor Session object. Raises a RuntimeError if the transaction has not been started. ```python def get_driver_session(self) -> AsyncIOMotorClientSession: """Return the underlying Motor Session""" if not self._transaction_started: raise RuntimeError("transaction not started") return self.session.get_driver_session() ``` -------------------------------- ### Curl Request for Non-existent Tree Source: https://art049.github.io/odmantic/usage_fastapi Example using curl to request a tree with an ID that does not exist in the database. This demonstrates the expected 404 Not Found response. ```bash curl http://localhost:8080/trees/f0f0f0f0f0f0f0f0f0f0f0f0 ``` -------------------------------- ### Get the underlying Motor Session Source: https://art049.github.io/odmantic/api_reference/session Retrieves the raw Motor session object. Raises a RuntimeError if the session has not been started. ```python def get_driver_session(self) -> AsyncIOMotorClientSession: """Return the underlying Motor Session""" if self.session is None: raise RuntimeError("session not started") return self.session ``` -------------------------------- ### Create Sync Engine with Custom Client Source: https://art049.github.io/odmantic/engine Initialize a SyncEngine with a custom PyMongoClient and specify a database name. ```python from pymongo import MongoClient from odmantic import SyncEngine client = MongoClient("mongodb://localhost:27017/") engine = SyncEngine(client=client, database="example_db") ``` -------------------------------- ### Start a new transaction Source: https://art049.github.io/odmantic/api_reference/engine Get a new transaction for the engine to aggregate sequential operations. MongoDB transactions are only supported on replicated clusters. ```APIDOC ## `transaction()` ### Description Get a new transaction for the engine to aggregate sequential operations. ### Returns - `SyncTransaction`: a new transaction object ### Example usage ```python engine = SyncEngine(...) with engine.transaction() as transaction: john = transaction.find(User, User.name == "John") john.name = "Doe" transaction.save(john) transaction.commit() ``` ### Warning MongoDB transaction are only supported on replicated clusters: either directly a replicaSet or a sharded cluster with replication enabled. ``` -------------------------------- ### Get Driver Session in odmantic Source: https://art049.github.io/odmantic/api_reference/session Retrieves the underlying PyMongo Session object. This is useful for advanced operations or when direct interaction with the driver is needed. It raises a RuntimeError if a transaction has not been started. ```python def get_driver_session(self) -> ClientSession: """Return the underlying PyMongo Session""" if not self._transaction_started: raise RuntimeError("transaction not started") return self.session.get_driver_session() ``` -------------------------------- ### Create Async Engine with Custom Client Source: https://art049.github.io/odmantic/engine Initialize an AIOEngine with a custom AsyncIOMotorClient and specify a database name. ```python from motor.motor_asyncio import AsyncIOMotorClient from odmantic import AIOEngine client = AsyncIOMotorClient("mongodb://localhost:27017/") engine = AIOEngine(client=client, database="example_db") ``` -------------------------------- ### Initialize SyncEngine Source: https://art049.github.io/odmantic/api_reference/engine Instantiate the synchronous engine. A default MongoClient is created if none is provided. ```python engine = SyncEngine(...) ``` -------------------------------- ### `__init__` constructor Source: https://art049.github.io/odmantic/api_reference/engine Initializes the Engine with an optional AsyncIO motor client and a database name. ```APIDOC ## `__init__(client=None, database='test')` ### Description Engine constructor. ### Parameters #### Path Parameters - `client` (Union[AsyncIOMotorClient, None]) - Optional - instance of an AsyncIO motor client. If None, a default one will be created - `database` (str) - Optional - name of the database to use. Default: 'test' ``` -------------------------------- ### Get Field Key Name and Reference Source: https://art049.github.io/odmantic/raw_query_usage Use the unary '+' operator on a model field to get its key name. Double the operator ('++') to get the field reference name, useful for aggregation pipelines. ```python from odmantic import Field, Model class User(Model): name: str = Field(key_name="username") print(+User.name) #> username print(++User.name) #> $username ``` -------------------------------- ### __init__ Source: https://art049.github.io/odmantic/api_reference/engine Initializes the ODMantic Engine. It can optionally take a PyMongo client instance and a database name. ```APIDOC ## __init__(client=None, database='test') ### Description Engine constructor. ### Parameters #### Path Parameters - **client** (Union[MongoClient, None]) - Optional - instance of a PyMongo client. If None, a default one will be created - **database** (str) - Optional - name of the database to use ### Source Code ```python def __init__( self, client: "Union[MongoClient, None]" = None, database: str = "test", ): """Engine constructor. Args: client: instance of a PyMongo client. If None, a default one will be created database: name of the database to use """ if client is None: client = MongoClient() super().__init__(client=client, database=database) ``` ``` -------------------------------- ### Remove Continuously Changing Example Source: https://art049.github.io/odmantic/changelog Removes an example for DateTime objects that was subject to continuous changes. ```python Remove continuously changing example for DateTime objects ``` -------------------------------- ### Initialize Odmantic Engine Source: https://art049.github.io/odmantic/api_reference/engine Constructs an Engine instance. If no PyMongo client is provided, a default one is created. Specify the database name to use. ```python def __init__( self, client: "Union[MongoClient, None]" = None, database: str = "test", ): """Engine constructor. Args: client: instance of a PyMongo client. If None, a default one will be created database: name of the database to use """ if client is None: client = MongoClient() super().__init__(client=client, database=database) ``` -------------------------------- ### Create Publisher Instances Source: https://art049.github.io/odmantic Create instances of the ODMantic model. Required fields must be provided. Optional fields will default to `None` if not specified. ```python instances = [ Publisher(name="HarperCollins", founded=1989, location="US"), Publisher(name="Hachette Livre", founded=1826, location="FR"), Publisher(name="Lulu", founded=2002) ] ``` -------------------------------- ### Fetch Multiple Instances as List (Sync) Source: https://art049.github.io/odmantic/engine Retrieve all `Player` instances not matching 'Starcraft' into a list using `list(engine.find)`. Use with caution for large datasets. ```python from odmantic import SyncEngine, Model class Player(Model): name: str game: str engine = SyncEngine() players = list(engine.find(Player, Player.game != "Starcraft")) print(players) #> [ #> Player(id=ObjectId(...), name="Leeroy Jenkins", game="World of Warcraft"), #> Player(id=ObjectId(...), name="Shroud", game="Counter-Strike"), #> ] ``` -------------------------------- ### Initialize AIOEngine Source: https://art049.github.io/odmantic/usage_fastapi Creates an instance of AIOEngine, which is responsible for performing database operations. ```python engine = AIOEngine() ``` -------------------------------- ### Session.start() Source: https://art049.github.io/odmantic/api_reference/session Initiates a database transaction. This method should be called before performing operations that need to be part of a transaction. ```APIDOC ## start() ### Description Initiate the transaction. ### Method ```python def start(self) -> None: """Initiate the transaction.""" if self._transaction_started: raise RuntimeError("Transaction already started") if not self._session_provided: self.session.start() assert self.session.session is not None self._transaction_context = self.session.session.start_transaction().__enter__() self._transaction_started = True ``` ``` -------------------------------- ### FastAPI Endpoint to Get Tree by ID Source: https://art049.github.io/odmantic/usage_fastapi Defines a FastAPI GET endpoint that accepts a tree ID as a path parameter. It uses ODMantic's ObjectId for validation and retrieves a single tree document from the database. Raises a 404 HTTPException if the tree is not found. ```python @app.get("/trees/{id}", response_model=Tree) async def get_tree_by_id(id: ObjectId, ): tree = await engine.find_one(Tree, Tree.id == id) if tree is None: raise HTTPException(404) return tree ``` -------------------------------- ### SyncEngine.transaction() Source: https://art049.github.io/odmantic/api_reference/engine Get a new transaction for the engine to aggregate sequential operations. ```APIDOC ## SyncEngine.transaction() ### Description Get a new transaction for the engine to aggregate sequential operations. ### Returns - a new transaction object ### Example usage: ```python engine = SyncEngine(...) with engine.transaction() as transaction: john = transaction.find(User, User.name == "John") john.name = "Doe" transaction.save(john) transaction.commit() ``` ### Warning: MongoDB transaction are only supported on replicated clusters: either directly a replicaSet or a sharded cluster with replication enabled. ``` -------------------------------- ### get_driver_session Source: https://art049.github.io/odmantic/api_reference/session Retrieves the underlying PyMongo Session object. Raises a RuntimeError if the session has not been started. ```APIDOC ## `get_driver_session()` ### Description Return the underlying PyMongo Session. ### Method ```python def get_driver_session(self) -> ClientSession: """Return the underlying PyMongo Session""" if self.session is None: raise RuntimeError("session not started") return self.session ``` ``` -------------------------------- ### Instantiate and Save Book and Author Data Source: https://art049.github.io/odmantic/modeling Create instances of `Author` and `Book` models, linking them via `author_ids`. Persist these instances to the database using `AIOEngine`. Authors and books must be saved separately due to the manual relationship. ```python david = Author(name="David Beazley") brian = Author(name="Brian K. Jones") python_cookbook = Book( title="Python Cookbook", pages=706, author_ids=[david.id, brian.id] ) python_essentials = Book( title="Python Essential Reference", pages=717, author_ids=[brian.id] ) engine = AIOEngine() await engine.save_all((david, brian)) await engine.save_all((python_cookbook, python_essentials)) ``` -------------------------------- ### Count Documents Source: https://art049.github.io/odmantic/api_reference/session Gets the count of documents matching a query. Accepts query filters. ```python def count( self, model: Type[ODMEngine.ModelType], *queries: Union[QueryExpression, Dict, bool], ) -> int: """Get the count of documents matching a query Args: model: model to perform the operation on *queries: query filters to apply Returns: number of document matching the query """ return self.engine.count( model, *queries, session=self.engine._get_session(self) ) ``` -------------------------------- ### Create trees using HTTPie Source: https://art049.github.io/odmantic/usage_fastapi Creates new 'Tree' instances in the database using HTTPie. Requires specifying the name, discovery year, and average size. ```bash http PUT localhost:8080/trees/ name="Spruce" discovery_year=1995 average_size=10.2 http PUT localhost:8080/trees/ name="Pine" discovery_year=1850 average_size=5 ``` -------------------------------- ### Fetch Multiple Instances as List (Async) Source: https://art049.github.io/odmantic/engine Retrieve all `Player` instances not matching 'Starcraft' into a list using `await engine.find`. Use with caution for large datasets. ```python from odmantic import AIOEngine, Model class Player(Model): name: str game: str engine = AIOEngine() players = await engine.find(Player, Player.game != "Starcraft") print(players) #> [ #> Player(id=ObjectId(...), name="Leeroy Jenkins", game="World of Warcraft"), #> Player(id=ObjectId(...), name="Shroud", game="Counter-Strike"), #> ] ``` -------------------------------- ### transaction() Source: https://art049.github.io/odmantic/api_reference/engine Get a new transaction for the engine to aggregate sequential operations. MongoDB transactions are only supported on replicated clusters. ```APIDOC ## `transaction()` ### Description Get a new transaction for the engine to aggregate sequential operations. ### Returns - `AIOTransaction`: a new transaction object ### Example usage ```python engine = AIOEngine(...) async with engine.transaction() as transaction: john = transaction.find(User, User.name == "John") john.name = "Doe" await transaction.save(john) await transaction.commit() ``` ### Warning MongoDB transaction are only supported on replicated clusters: either a replicaSet or a sharded cluster with replication enabled. ``` -------------------------------- ### End an ODMantic session Source: https://art049.github.io/odmantic/api_reference/session Closes the logical Mongo session and releases associated resources. Raises a RuntimeError if the session has not been started. ```python async def end(self) -> None: """Finish the logical session.""" if self.session is None: raise RuntimeError("Session is not started") await self.session.end_session() self.session = None ``` -------------------------------- ### Connect to MongoDB with AIOEngine Source: https://art049.github.io/odmantic Initialize the AIOEngine to connect to a MongoDB instance. By default, it connects to a local instance on port 27017 and uses the 'test' database if none is specified. ```python from odmantic import AIOEngine engine = AIOEngine() ``` -------------------------------- ### Count instances with AIOEngine Source: https://art049.github.io/odmantic/engine Use `engine.count` to get the total number of instances or filter them. Supports combining multiple queries. ```python from odmantic import AIOEngine, Model class Player(Model): name: str game: str engine = AIOEngine() player_count = await engine.count(Player) print(player_count) #> 4 cs_count = await engine.count(Player, Player.game == "Counter-Strike") print(cs_count) #> 1 valorant_count = await engine.count(Player, Player.game == "Valorant") print(valorant_count) #> 0 ``` -------------------------------- ### Get Collection Name from Model Source: https://art049.github.io/odmantic/raw_query_usage Use the unary '+' operator on a model class to retrieve its associated collection name. ```python from odmantic import Model class User(Model): name: str collection_name = +User print(collection_name) #> user ``` -------------------------------- ### Get Collection from AIOEngine Source: https://art049.github.io/odmantic/api_reference/engine Retrieves the motor collection associated with a given ODMantic model. This is useful for performing low-level operations on the collection. ```python def get_collection(self, model: Type[ModelType]) -> "AsyncIOMotorCollection": """Get the motor collection associated to a Model. Args: model: model class Returns: the AsyncIO motor collection object """ return self.database[model.__collection__] ``` -------------------------------- ### Count Documents with AIOSessionBase Source: https://art049.github.io/odmantic/api_reference/session Gets the count of documents matching a query. It calls the engine's count method with the session context. ```python async def count( self, model: Type[ODMEngine.ModelType], *queries: Union[QueryExpression, Dict, bool], ) -> int: """Get the count of documents matching a query Args: model: model to perform the operation on *queries: query filters to apply Returns: number of document matching the query """ return await self.engine.count( model, *queries, session=self.engine._get_session(self) ) ``` -------------------------------- ### Initialize Index with Fields Source: https://art049.github.io/odmantic/api_reference The `Index` constructor takes fields to build the index. It supports single fields, sort expressions (like `desc`), and custom names. The `unique` parameter enforces uniqueness. ```python def __init__( self, *fields: Union[FieldProxyAny, SortExpression], unique: bool = False, name: Optional[str] = None, ) -> None: """Declare an ODM index in the Model.Config.indexes generator. Example usage: ```python from odmantic import Model, Index from odmantic.query import desc class Player(Model): name: str score: int model_config = { "indexes": lambda: [Index(Player.name, desc(Player.score))], } ``` Args: *fields (Any | SortExpression | str): fields to build the index with unique: build a unique index name: specify an optional custom index name """ self.fields = cast(Tuple[Union[SortExpression, FieldProxy], ...], fields) self.unique = unique self.name = name ``` -------------------------------- ### Fetch Single Instance (Sync) Source: https://art049.github.io/odmantic/engine Use `engine.find_one` to retrieve at most one instance matching the criteria. Returns `None` if no instance is found. Requires `SyncEngine`. ```python from odmantic import Model, SyncEngine class Player(Model): name: str game: str engine = SyncEngine() player = engine.find_one(Player, Player.name == "Serral") print(repr(player)) #> Player(id=ObjectId(...), name="Serral", game="Starcraft") another_player = engine.find_one( Player, Player.name == "Player_Not_Stored_In_Database" ) print(another_player) #> None ``` -------------------------------- ### Get all trees Source: https://art049.github.io/odmantic/usage_fastapi Retrieves a list of all tree instances stored in the database. This endpoint uses the `engine.find` method to fetch all `Tree` objects. ```APIDOC ## GET /trees/ ### Description Retrieves a list of all tree instances stored in the database. ### Method GET ### Endpoint /trees/ ### Response #### Success Response (200) - **trees** (List[Tree]) - A list of Tree instances. ### Response Example ```json [ { "average_size": 10.2, "discovery_year": 1995, "id": "5f8c8266f1d33aa1012f3082", "name": "Spruce" }, { "average_size": 5.0, "discovery_year": 1850, "id": "5f8c8266f1d33aa1012f3083", "name": "Pine" } ] ``` ``` -------------------------------- ### Fetch Multiple Instances with Sort Source: https://art049.github.io/odmantic/engine Order query results by multiple fields, using ascending for `name` and descending for `game`. ```python engine.find(Player, sort=(Player.name, Player.game.desc())) ``` -------------------------------- ### Commit Transaction in odmantic Session Source: https://art049.github.io/odmantic/api_reference/session Use this method to finalize and save changes within the current transaction. It raises a RuntimeError if the transaction has not been started. ```python def commit(self) -> None: """Commit the changes and close the transaction.""" if not self._transaction_started: raise RuntimeError("Transaction not started") assert self.session.session is not None self.session.session.commit_transaction() self._transaction_started = False if not self._session_provided: self.session.end() ``` -------------------------------- ### Abort Transaction in odmantic Session Source: https://art049.github.io/odmantic/api_reference/session Use this method to discard any pending changes and close the current transaction. It raises a RuntimeError if the transaction has not been started. ```python def abort(self) -> None: """Discard the changes and drop the transaction.""" if not self._transaction_started: raise RuntimeError("Transaction not started") assert self.session.session is not None self.session.session.abort_transaction() self._transaction_started = False if not self._session_provided: self.session.end() ``` -------------------------------- ### Example Usage of SyncEngine Transaction as Context Manager Source: https://art049.github.io/odmantic/api_reference/session Demonstrates how to use the `transaction` method of `SyncEngine` as a context manager for atomic operations. Ensure your MongoDB is configured as a replica set or sharded cluster. ```python engine = SyncEngine(...) with engine.transaction() as transaction: john = transaction.find(User, User.name == "John") john.name = "Doe" transaction.save(john) transaction.commit() ``` -------------------------------- ### Fetch Single Instance with Sort (Async) Source: https://art049.github.io/odmantic/engine Fetch a single `Player` instance, ordered by `name` in ascending order using the `sort` parameter. ```python await engine.find_one(Player, sort=Player.name) ``` -------------------------------- ### Get PyMongo Collection Source: https://art049.github.io/odmantic/api_reference/engine Retrieves the PyMongo collection object associated with a given Model class. This is useful for performing lower-level database operations. ```python def get_collection(self, model: Type[ModelType]) -> "Collection": """Get the pymongo collection associated to a Model. Args: model: model class Returns: the pymongo collection object """ collection = self.database[model.__collection__] return collection ``` -------------------------------- ### Get Driver Session from ODMantic Session Source: https://art049.github.io/odmantic/api_reference/engine Helper method to extract the underlying driver session (e.g., AsyncIOMotorClientSession) from an ODMantic session object. ```python @staticmethod def _get_session( session: Union[AIOSessionType, AIOSessionBase], ) -> Optional[AsyncIOMotorClientSession]: if isinstance(session, (AIOSession, AIOTransaction)): return session.get_driver_session() assert not isinstance(session, AIOSessionBase) # Abstract class return session ``` -------------------------------- ### Python 3.10 Union Syntax Support Source: https://art049.github.io/odmantic/changelog Demonstrates the support for Python 3.10's Union syntax for type hints. ```python name: str | None = None ```