### Run a Task Queue with a Runner Source: https://github.com/beanieodm/beanie/blob/main/docs/batteries/queue.md Example of setting up and starting a Runner to process tasks. Ensure Task classes are correctly defined and passed to the Runner. ```python from beanie_batteries_queue import Task, Runner class ExampleTask(Task): data: str async def run(self): self.data = self.data.upper() await self.save() runner = Runner(task_classes=[ExampleTask]) runner.start() ``` -------------------------------- ### Install Beanie with All Optional Dependencies Source: https://github.com/beanieodm/beanie/blob/main/docs/getting-started.md Install Beanie with all available optional dependencies for comprehensive support. ```shell pip install "beanie[gssapi,aws,ocsp,snappy,srv,zstd,encryption]" ``` -------------------------------- ### Install Beanie with Queue Support Source: https://github.com/beanieodm/beanie/blob/main/docs/batteries/queue.md Command to install Beanie with the necessary dependencies for the queue system. ```shell pip install beanie[queue] ``` -------------------------------- ### Start Documentation Server Source: https://github.com/beanieodm/beanie/blob/main/docs/development.md Starts a local server to preview documentation changes. Visit the printed address (usually localhost:8000) in your browser. Auto-recompiling may not work for all users. ```shell pydoc-markdown --server ``` -------------------------------- ### Install Beanie with Snappy Compression Source: https://github.com/beanieodm/beanie/blob/main/docs/getting-started.md Install Beanie with the 'snappy' extra for wire protocol compression using Snappy. ```shell pip install "beanie[snappy]" ``` -------------------------------- ### Install Beanie with Documentation Dependencies Source: https://github.com/beanieodm/beanie/blob/main/docs/development.md Installs Beanie and its documentation build dependencies in a virtual environment. This command should be run from the root directory of the Beanie project. ```shell pip install -e .[doc] ``` -------------------------------- ### Install Beanie with OCSP Support Source: https://github.com/beanieodm/beanie/blob/main/docs/getting-started.md Install Beanie with the 'ocsp' extra for OCSP support. ```shell pip install "beanie[ocsp]" ``` -------------------------------- ### Install Beanie with GSSAPI Support Source: https://github.com/beanieodm/beanie/blob/main/docs/getting-started.md Install Beanie with the 'gssapi' extra for GSSAPI authentication support. ```shell pip install "beanie[gssapi]" ``` -------------------------------- ### Install Beanie with Zstandard Compression Source: https://github.com/beanieodm/beanie/blob/main/docs/getting-started.md Install Beanie with the 'zstd' extra for wire protocol compression using Zstandard. ```shell pip install "beanie[zstd]" ``` -------------------------------- ### Install Beanie with Test Dependencies Source: https://github.com/beanieodm/beanie/blob/main/docs/development.md Installs Beanie and its testing dependencies in a virtual environment. This command should be run from the root directory of the Beanie project. ```shell pip install -e .[test] ``` -------------------------------- ### Install Beanie with AWS Support Source: https://github.com/beanieodm/beanie/blob/main/docs/getting-started.md Install Beanie with the 'aws' extra for MONGODB-AWS authentication support. ```shell pip install "beanie[aws]" ``` -------------------------------- ### Install Beanie with Encryption Support Source: https://github.com/beanieodm/beanie/blob/main/docs/getting-started.md Install Beanie with the 'encryption' extra for Client-Side Field Level Encryption. ```shell pip install "beanie[encryption]" ``` -------------------------------- ### Install Git Pre-commit Hooks Source: https://github.com/beanieodm/beanie/blob/main/docs/development.md Sets up pre-commit hooks to ensure code consistency using Black and Ruff. Run this command in the root directory of the Beanie project. ```shell pre-commit install ``` -------------------------------- ### Install Beanie with PIP Source: https://github.com/beanieodm/beanie/blob/main/docs/getting-started.md Use this command to install the base Beanie package via pip. ```shell pip install beanie ``` -------------------------------- ### Basic Beanie Document Example Source: https://github.com/beanieodm/beanie/blob/main/README.md Demonstrates defining a Pydantic-based Document, initializing Beanie, creating a document instance, inserting it into the database, finding a document, and updating it. Requires an asynchronous context. ```python import asyncio from typing import Optional from pymongo import AsyncMongoClient from pydantic import BaseModel from beanie import Document, Indexed, init_beanie class Category(BaseModel): name: str description: str class Product(Document): name: str # You can use normal types just like in pydantic description: Optional[str] = None price: Indexed(float) # You can also specify that a field should correspond to an index category: Category # You can include pydantic models as well # This is an asynchronous example, so we will access it from an async function async def example(): # Beanie uses PyMongo async client under the hood client = AsyncMongoClient("mongodb://user:pass@host:27017") # Initialize beanie with the Product document class await init_beanie(database=client.db_name, document_models=[Product]) chocolate = Category(name="Chocolate", description="A preparation of roasted and ground cacao seeds.") # Beanie documents work just like pydantic models tonybar = Product(name="Tony's", price=5.95, category=chocolate) # And can be inserted into the database await tonybar.insert() # You can find documents with pythonic syntax product = await Product.find_one(Product.price < 10) # And update them await product.set({Product.name:"Gold bar"}) if __name__ == "__main__": asyncio.run(example()) ``` -------------------------------- ### Install Beanie with SRV Support Source: https://github.com/beanieodm/beanie/blob/main/docs/getting-started.md Install Beanie with the 'srv' extra to support mongodb+srv:// URIs. ```shell pip install "beanie[srv]" ``` -------------------------------- ### Install Beanie with Poetry Source: https://github.com/beanieodm/beanie/blob/main/docs/getting-started.md Use this command to add Beanie to your project dependencies using Poetry. ```shell poetry add beanie ``` -------------------------------- ### Task Priority Example Source: https://github.com/beanieodm/beanie/blob/main/docs/batteries/queue.md Illustrates how to assign priorities (LOW, MEDIUM, HIGH) to tasks and how they are processed in order. HIGH priority tasks are processed before MEDIUM and LOW. ```python from beanie_batteries_queue import Priority task1 = SimpleTask(s="test1", priority=Priority.LOW) await task1.push() task2 = SimpleTask(s="test2", priority=Priority.HIGH) await task2.push() async for task in SimpleTask.queue(): assert task.s == "test2" await task.finish() break ``` -------------------------------- ### Beanie Document Models for Migration Example Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/migrations.md Defines the 'OldNote' and 'Note' document models, along with their associated 'Tag' and 'OldTag' Pydantic models, used in migration examples. ```python from pydantic.main import BaseModel from beanie import Document, iterative_migration class OldTag(BaseModel): color: str name: str class Tag(BaseModel): color: str title: str class OldNote(Document): title: str tag: OldTag class Settings: name = "notes" class Note(Document): title: str tag: Tag class Settings: name = "notes" ``` -------------------------------- ### Define and run a processing task Source: https://github.com/beanieodm/beanie/blob/main/docs/batteries/queue.md Create a custom task by inheriting from `Task` and implementing the `run` method. Instantiate and start the queue to process tasks. ```python from beanie_batteries_queue import Task class ProcessTask(Task): data: str async def run(self): # Implement the logic for processing the task print(f"Processing task with data: {self.data}") self.data = self.data.upper() await self.save() ``` ```python queue = ProcessTask.queue() await queue.start() ``` -------------------------------- ### Cache Usage Example Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/cache.md Demonstrates how Beanie ODM uses the cache. The first query fetches data from the database, subsequent identical queries use the cache, and queries after expiration retrieve data from the database again. ```python # on the first call it will go to the database samples = await Sample.find(num>10).to_list() # on the second - it will use cache instead samples = await Sample.find(num>10).to_list() await asyncio.sleep(15) # if the expiration time was reached it will go to the database again samples = await Sample.find(num>10).to_list() ``` -------------------------------- ### Beanie Migration File Structure Source: https://context7.com/beanieodm/beanie/llms.txt Example structure for Beanie migration files, defining old and new document schemas and migration logic for forward and backward passes using `iterative_migration`. ```python # migrations/20240315123456_add_field.py from beanie import Document, iterative_migration, free_fall_migration class OldUser(Document): name: str class Settings: name = "users" class NewUser(Document): name: str email: str = "" class Settings: name = "users" class Forward: @iterative_migration() async def add_email_field(self, input_document: OldUser, output_document: NewUser): output_document.email = f"{input_document.name.lower()}@example.com" class Backward: @iterative_migration() async def remove_email_field(self, input_document: NewUser, output_document: OldUser): pass # email field simply won't be included ``` -------------------------------- ### Initialize and start a Worker for multiple task types Source: https://github.com/beanieodm/beanie/blob/main/docs/batteries/queue.md Use the `Worker` class to manage and process multiple task models concurrently. Provide a list of task classes to the `Worker` constructor. ```python from beanie_batteries_queue import Task, Worker class ProcessTask(Task): data: str async def run(self): self.data = self.data.upper() await self.save() class AnotherTask(Task): data: str async def run(self): self.data = self.data.upper() await self.save() worker = Worker(task_classes=[ProcessTask, AnotherTask]) await worker.start() ``` -------------------------------- ### Access and Get Document by ID Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/defining-a-document.md Demonstrates how to find a document and access its `id` field. The `get` method can be used to retrieve a document directly by its ID. ```python class Sample(Document): num: int description: str foo = await Sample.find_one(Sample.num > 5) print(foo.id) # This will print id bar = await Sample.get(foo.id) # get by id ``` -------------------------------- ### Initialize and start a Runner for parallel processing Source: https://github.com/beanieodm/beanie/blob/main/docs/batteries/queue.md Utilize the `Runner` class to execute multiple workers across separate processes, optimizing for CPU-intensive tasks and leveraging multi-core processors. ```python from beanie_batteries_queue import Task, Runner class ProcessTask(Task): data: str async def run(self): self.data = self.data.upper() await self.save() class AnotherTask(Task): data: str async def run(self): self.data = self.data.upper() await self.save() runner = Runner(task_classes=[ProcessTask, AnotherTask]) runner.start() ``` -------------------------------- ### Insert Documents into a Collection Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/views.md Insert multiple documents into the `Bike` collection. This setup is necessary before querying the `Metrics` view which aggregates data from `Bike`. ```python await Bike(type="Mountain", frame_size=54, is_new=True).insert() await Bike(type="Mountain", frame_size=60, is_new=False).insert() await Bike(type="Road", frame_size=52, is_new=True).insert() await Bike(type="Road", frame_size=54, is_new=True).insert() await Bike(type="Road", frame_size=58, is_new=False).insert() ``` -------------------------------- ### Beanie Document Example Source: https://github.com/beanieodm/beanie/blob/main/docs/index.md Demonstrates defining a Beanie Document with Pydantic models, including indexed fields and nested Pydantic models. Initialization requires an async MongoDB client and document models. ```python import asyncio from typing import Optional from pymongo import AsyncMongoClient from pydantic import BaseModel from beanie import Document, Indexed, init_beanie class Category(BaseModel): name: str description: str class Product(Document): name: str # You can use normal types just like in pydantic description: Optional[str] = None price: Indexed(float) # You can also specify that a field should correspond to an index category: Category # You can include pydantic models as well # This is an asynchronous example, so we will access it from an async function async def example(): # Beanie uses PyMongo async client under the hood client = AsyncMongoClient("mongodb://user:pass@host:27017") # Initialize beanie with the Product document class await init_beanie(database=client.db_name, document_models=[Product]) chocolate = Category(name="Chocolate", description="A preparation of roasted and ground cacao seeds.") # Beanie documents work just like pydantic models tonybar = Product(name="Tony's", price=5.95, category=chocolate) # And can be inserted into the database await tonybar.insert() # You can find documents with pythonic syntax product = await Product.find_one(Product.price < 10) # And update them await product.set({Product.name:"Gold bar"}) if __name__ == "__main__": asyncio.run(example()) ``` -------------------------------- ### Get First or None Source: https://context7.com/beanieodm/beanie/llms.txt Retrieves the first document matching the criteria, or None if no documents are found. Useful for unique or first-occurrence checks. ```python # First or None first = await Product.find(Product.price < 1).first_or_none() ``` -------------------------------- ### Configure Runner Indefinite Run Source: https://github.com/beanieodm/beanie/blob/main/docs/batteries/queue.md Control whether the runner's start method returns immediately or runs while workers are active. The default is True. ```python runner = Runner(task_classes=[ProcessTask, AnotherTask], run_indefinitely=False) runner.start() ``` -------------------------------- ### Default IPv4Address Encoding Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/defining-a-document.md Shows the default behavior where IPv4Address is converted to String. No special setup is required for this default. ```python from ipaddress import IPv4Address class Sample(Document): ip: IPv4Address ``` -------------------------------- ### Task Dependencies: Processing Logic Source: https://github.com/beanieodm/beanie/blob/main/docs/batteries/queue.md Example demonstrating how task dependencies affect processing. A task with an unfinished dependency will not be popped from the queue. ```python from beanie_batteries_queue import State task1 = SimpleTask(s="test1") await task1.push() task2 = TaskWithDirectDependency(s="test2", direct_dependency=task1) await task2.push() task_from_queue = await TaskWithDirectDependency.pop() assert task_from_queue is None # task2 is not popped from the queue because task1 is not finished yet await task1.finish() task_from_queue = await TaskWithDirectDependency.pop() assert task_from_queue is not None # task2 is popped from the queue because task1 is finished ``` -------------------------------- ### Update Document Examples in Beanie Source: https://context7.com/beanieodm/beanie/llms.txt Demonstrates various methods for updating documents, including fetch-and-modify, atomic field updates, and query-based updates. Use these for modifying existing documents in your MongoDB collections. ```python from beanie import Document from beanie.operators import Set, Inc, Push, Pull class Product(Document): name: str price: float quantity: int = 0 tags: list[str] = [] async def update_examples(): # Fetch and modify approach product = await Product.find_one(Product.name == "Tony's") product.price = 6.95 await product.save() # Full document update # Replace - fails if document doesn't exist product.price = 7.95 await product.replace() # Atomic field updates using set() await product.set({Product.price: 5.95}) # Increment numeric fields await product.inc({Product.quantity: 10}) # Multiple operations in one update await product.update( Set({Product.price: 4.95}), Inc({Product.quantity: 5}) ) # Update directly from query (without fetching) await Product.find_one(Product.name == "Tony's").update( Set({Product.price: 3.95}) ) # Update many documents await Product.find( Product.price < 2 ).update(Inc({Product.price: 0.50})) # Update all documents await Product.update_all(Set({Product.quantity: 0})) # Upsert - insert if not found await Product.find_one(Product.name == "New Product").upsert( Set({Product.price: 9.99}), on_insert=Product(name="New Product", price=9.99) ) # Get updated document back from beanie import UpdateResponse updated = await Product.find_one(Product.name == "Tony's").update( Set({Product.price: 5.50}), response_type=UpdateResponse.NEW_DOCUMENT ) print(updated.price) # 5.50 ``` -------------------------------- ### Delete Document Examples in Beanie Source: https://context7.com/beanieodm/beanie/llms.txt Illustrates how to delete single documents, multiple documents based on a query, or all documents within a collection. Use these for removing unwanted data. ```python from beanie import Document class Product(Document): name: str price: float category: str async def delete_examples(): # Delete a fetched document product = await Product.find_one(Product.name == "Expired Item") if product: await product.delete() # Delete directly from query await Product.find_one(Product.name == "Old Product").delete() # Delete many matching documents await Product.find(Product.category == "Discontinued").delete() # Delete all documents in collection await Product.delete_all() # Or equivalently: await Product.find_all().delete() ``` -------------------------------- ### Free Fall Migration Example Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/migrations.md This snippet demonstrates a free fall migration function that renames a field from 'name' to 'title' and replaces old documents with new ones. It requires the `session` argument for rollback capabilities. ```python from pydantic.main import BaseModel from beanie import Document, free_fall_migration class Tag(BaseModel): color: str name: str class OldNote(Document): name: str tag: Tag class Settings: name = "notes" class Note(Document): title: str tag: Tag class Settings: name = "notes" class Forward: @free_fall_migration(document_models=[OldNote, Note]) async def name_to_title(self, session): async for old_note in OldNote.find_all(): new_note = Note( id=old_note.id, title=old_note.name, tag=old_note.tag ) await new_note.replace(session=session) class Backward: @free_fall_migration(document_models=[OldNote, Note]) async def title_to_name(self, session): async for old_note in Note.find_all(): new_note = OldNote( id=old_note.id, name=old_note.title, tag=old_note.tag ) await new_note.replace(session=session) ``` -------------------------------- ### Simple Field Rename Migration (Forward) Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/migrations.md Example of a forward migration to rename a field from 'name' to 'title'. It maps the input document's 'name' to the output document's 'title'. ```python class Forward: @iterative_migration() async def name_to_title( self, input_document: OldNote, output_document: Note ): output_document.title = input_document.name ``` -------------------------------- ### Simple Field Rename Migration (Backward) Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/migrations.md Example of a backward migration to revert a field rename from 'title' to 'name'. It maps the input document's 'title' back to the output document's 'name'. ```python class Backward: @iterative_migration() async def title_to_name( self, input_document: Note, output_document: OldNote ): output_document.name = input_document.title ``` -------------------------------- ### Show Migration Help Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/migrations.md Displays the help message for the migrate command, listing all available parameters and their descriptions. ```shell beanie migrate --help ``` -------------------------------- ### Register a Synchronous Before Event Action in Beanie Source: https://github.com/beanieodm/beanie/blob/main/docs/articles/1.8.0.md Use the `@before_event` decorator with an event type (e.g., `Insert`) to register a synchronous method that runs before a document event occurs. This example capitalizes a string field before insertion. ```python from beanie import Insert, Replace class Sample(Document): num: int name: str @before_event(Insert) def capitalize_name(self): self.name = self.name.capitalize() ``` -------------------------------- ### Create and Save Linked Documents Source: https://context7.com/beanieodm/beanie/llms.txt Demonstrates creating and saving documents with various link configurations, including cascade writes using WriteRules.WRITE. ```python async def relations_examples(): # Create linked documents author = Author(name="J.K. Rowling") await author.insert() publisher = Publisher(name="Bloomsbury", location="London") await publisher.insert() # Create book with links (author must be saved first) book = Book( title="Harry Potter", author=author, publisher=publisher ) await book.insert() # Insert with cascade - saves linked docs too new_author = Author(name="George Orwell") new_book = Book(title="1984", author=new_author) await new_book.save(link_rule=WriteRules.WRITE) ``` -------------------------------- ### Initialize Beanie with Document and View Models Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/views.md Initialize Beanie by providing the database client and a list of document and view models. Set `recreate_views=True` to ensure views are recreated on initialization. ```python from pymongo import AsyncMongoClient from beanie import init_beanie async def main(): uri = "mongodb://beanie:beanie@localhost:27017" client = AsyncMongoClient(uri) db = client.bikes await init_beanie( database=db, document_models=[Bike, Metrics], recreate_views=True, ) ``` -------------------------------- ### Initialize Beanie with String Paths Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/init.md Initialize Beanie ODM using string paths to document models instead of class objects. Ensure the paths are dot-separated. ```python await init_beanie( database=client.db_name, document_models=[ "app.models.DemoDocument", ], ) ``` -------------------------------- ### Task State Management: Finished Source: https://github.com/beanieodm/beanie/blob/main/docs/batteries/queue.md Demonstrates the lifecycle of a task, from creation to being marked as FINISHED. Tasks transition from CREATED to RUNNING upon retrieval and must be manually marked as FINISHED or FAILED. ```python from beanie_batteries_queue import State task = SimpleTask(s="test") await task.push() async for task in SimpleTask.queue(): assert task.state == State.RUNNING await task.finish() break task = await SimpleTask.find_one({"s": "test"}) assert task.state == State.FINISHED ``` -------------------------------- ### Get Document by ID in Beanie Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/find.md Fetch a single document by its unique ID using the `get()` method. This is a direct and efficient way to retrieve a specific document. ```python bar = await Product.get("608da169eb9e17281f0ab2ff") ``` -------------------------------- ### Initialize Beanie with Document Classes Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/init.md Initialize Beanie ODM by providing an Async PyMongo database instance and a list of document model classes. This sets up collections and indexes. ```python from beanie import init_beanie, Document from pymongo import AsyncMongoClient class Sample(Document): name: str async def init(): # Create Async PyMongo client client = AsyncMongoClient( "mongodb://user:pass@host:27017" ) # Initialize beanie with the Sample document class and a database await init_beanie(database=client.db_name, document_models=[Sample]) ``` -------------------------------- ### Get Distinct Field Values Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/find.md Use the `distinct()` method on `find()` or `find_many()` queries to get a list of unique values for a specified field. Note that `skip` and `limit` are ignored, and this method is terminal. ```python categories = await Product.find(Product.price < 10).distinct("category.name") ``` ```python names = await Product.find( Product.category.name == "Chocolate", fetch_links=True ).distinct("name") ``` -------------------------------- ### Initialize Beanie with Models Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/inheritance.md Initialize Beanie with your document models. Ensure all models in the inheritance chain are included. ```python client = AsyncMongoClient() await init_beanie(client.test_db, document_models=[Vehicle, Bicycle, Bike, Car, Bus, Owner]) ``` -------------------------------- ### Delete Linked Documents with Cascade Source: https://context7.com/beanieodm/beanie/llms.txt Example of deleting a document and controlling the deletion of linked documents using DeleteRules.DELETE_LINKS. ```python # Delete with cascade await book.delete(link_rule=DeleteRules.DELETE_LINKS) ``` -------------------------------- ### Process Tasks using SimpleTask.queue() Source: https://github.com/beanieodm/beanie/blob/main/docs/batteries/queue.md Demonstrates pushing a task and then consuming it using the async generator `SimpleTask.queue()`. The loop can be broken manually. ```python from beanie_batteries_queue import State # Producer task = SimpleTask(s="test") await task.push() # Consumer async for task in SimpleTask.queue(): assert task.s == "test" # Do some work await task.finish() break # Check that the task is finished task = await SimpleTask.find_one({"s": "test"}) assert task.state == State.FINISHED ``` -------------------------------- ### Get First Document or None in Beanie Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/find.md Retrieve the first document matching the criteria, or `None` if no documents are found, using the `.first_or_none()` method. ```python result = await Product.find(search_criteria).first_or_none() ``` -------------------------------- ### Create and Push Git Tag for Release Source: https://github.com/beanieodm/beanie/blob/main/docs/publishing.md Create a new Git tag for the release version and push it to the remote repository. Replace 'v1.xx.y' with the actual version number. ```bash git tag -a v1.xx.y -m "Release v1.xx.y" ``` ```bash git push origin v1.xx.y ``` -------------------------------- ### Process Tasks using SimpleTask.pop() Source: https://github.com/beanieodm/beanie/blob/main/docs/batteries/queue.md Shows how to push a task and then retrieve and process it using `SimpleTask.pop()`. This method is suitable for single-task retrieval. ```python from beanie_batteries_queue import State # Producer task = SimpleTask(s="test") await task.push() # Consumer task = await SimpleTask.pop() assert task.s == "test" # Do some work await task.finish() ``` -------------------------------- ### Complex Nested Field Migration (Forward) Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/migrations.md Forward migration example for changing a nested field, specifically renaming 'name' within 'tag' to 'title'. ```python class Forward: @iterative_migration() async def change_color( self, input_document: OldNote, output_document: Note ): output_document.tag.title = input_document.tag.name ``` -------------------------------- ### Complex Nested Field Migration (Backward) Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/migrations.md Backward migration example to revert the nested field change, renaming 'title' within 'tag' back to 'name'. ```python class Backward: @iterative_migration() async def change_title( self, input_document: Note, output_document: OldNote ): output_document.tag.name = input_document.tag.title ``` -------------------------------- ### Run Changelog Generation Script Source: https://github.com/beanieodm/beanie/blob/main/docs/publishing.md Execute the changelog generation script to create release notes. Ensure the script is updated with the correct current and new version numbers before running. ```bash python scripts/generate_changelog.py ``` -------------------------------- ### Insert Single and Multiple Documents Source: https://context7.com/beanieodm/beanie/llms.txt Demonstrates various methods for inserting single documents (insert, create, save, insert_one) and batch inserting multiple documents (insert_many). ```python from beanie import Document from pydantic import BaseModel class Category(BaseModel): name: str class Product(Document): name: str price: float category: Category async def insert_examples(): # Create document instances (not yet in database) chocolate = Category(name="Chocolate") tony_bar = Product(name="Tony's", price=5.95, category=chocolate) mars_bar = Product(name="Mars", price=1.50, category=chocolate) # Insert single document - returns self with id populated await tony_bar.insert() print(tony_bar.id) # ObjectId('...') # create() is an alias for insert() snickers = Product(name="Snickers", price=1.75, category=chocolate) await snickers.create() # save() inserts new documents or updates existing ones twix = Product(name="Twix", price=1.80, category=chocolate) await twix.save() # Inserts since it's new # Class method for single insert kit_kat = Product(name="Kit Kat", price=1.60, category=chocolate) await Product.insert_one(kit_kat) # Batch insert - more efficient for multiple documents products = [ Product(name="Bounty", price=1.40, category=chocolate), Product(name="Milky Way", price=1.30, category=chocolate), Product(name="Crunch", price=1.45, category=chocolate), ] result = await Product.insert_many(products) print(result.inserted_ids) # List of ObjectIds ``` -------------------------------- ### Define a Beanie Document Model Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/defining-a-document.md Inherit from `Document` to create a model that maps to a MongoDB collection. This example shows basic field definitions and custom collection settings. ```python from typing import Optional import pymongo from pydantic import BaseModel from beanie import Document, Indexed class Category(BaseModel): name: str description: str class Product(Document): # This is the model name: str description: Optional[str] = None price: Indexed(float, pymongo.DESCENDING) category: Category class Settings: name = "products" indexes = [ [ ("name", pymongo.TEXT), ("description", pymongo.TEXT), ], ] ``` -------------------------------- ### Fetch Linked Documents (Eager and Lazy Loading) Source: https://context7.com/beanieodm/beanie/llms.txt Illustrates fetching documents with links unresolved (DBRef), eagerly loaded (fetch_links=True), and lazily loaded on demand. ```python # Fetch without resolving links - links are DBRef objects book = await Book.find_one(Book.title == "Harry Potter") print(type(book.author)) # # Fetch with links resolved (eager loading) book = await Book.find_one( Book.title == "Harry Potter", fetch_links=True ) print(book.author.name) # "J.K. Rowling" # Fetch links on demand (lazy loading) book = await Book.find_one(Book.title == "Harry Potter") await book.fetch_all_links() print(book.author.name) ``` -------------------------------- ### Run All Forward Migrations Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/migrations.md Executes all pending forward migrations. This is the default behavior when no distance is specified. ```shell beanie migrate -uri 'mongodb+srv://user:pass@host' -db db -p relative/path/to/migrations/directory/ ``` -------------------------------- ### Example of Action Conflict Resolution with RAISE Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/actions.md Using `ActionConflictResolution.RAISE` will cause a `MergeConflictError` to be raised if both an explicit update and a before-event action attempt to modify the same field. This ensures strict control over updates. ```python from beanie import ( Document, Update, ActionConflictResolution, MergeConflictError, before_event, ) class StrictSample(Document): name: str counter: int = 0 @before_event(Update) def increment_counter(self): self.counter += 1 class Settings: action_conflict_resolution = ActionConflictResolution.RAISE sample = StrictSample(name="test") await sample.insert() # This works fine — no conflict (update touches "name", action touches "counter") await sample.set({StrictSample.name: "updated"}) ``` -------------------------------- ### Registering Before and After Event Actions Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/actions.md Use `@before_event` and `@after_event` decorators to register methods that execute before or after specific document events like Insert or Replace. Ensure necessary imports are included. ```python from beanie import Insert, Replace, before_event, after_event class Sample(Document): num: int name: str @before_event(Insert) def capitalize_name(self): self.name = self.name.capitalize() @after_event(Replace) def num_change(self): self.num -= 1 ``` -------------------------------- ### Create New Migration Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/migrations.md Use this command to generate a new migration file. Specify a name and the directory for migrations. The filename will include a timestamp. ```shell beanie new-migration -n migration_name -p relative/path/to/migrations/directory/ ``` -------------------------------- ### On-Save Validation Error Example Source: https://github.com/beanieodm/beanie/blob/main/docs/articles/1.8.0.md When `validate_on_save` is enabled, attempting a write operation with an invalid field value (e.g., incorrect type) will raise an error. This ensures data integrity at the point of persistence. ```python sample = await Sample.find_one(Sample.name == "Test") sample.num = "wrong value type" # Next call will raise an error await sample.replace() ``` -------------------------------- ### Insert a Single Document Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/insert.md Use `insert()` or `create()` on a document instance to save it to the database. `save()` can also be used for new documents. ```python await tonybar.insert() await marsbar.create() # does exactly the same as insert() ``` -------------------------------- ### Run All Backward Migrations Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/migrations.md Reverts all migrations. Use with caution, especially if transactions were not used during forward migrations. ```shell beanie migrate -uri 'mongodb+srv://user:pass@host' -db db -p relative/path/to/migrations/directory/ --backward ``` -------------------------------- ### Fetch Specific Link and Search by Linked Fields Source: https://context7.com/beanieodm/beanie/llms.txt Shows how to fetch a single specific link and how to query documents based on fields within linked documents, requiring fetch_links=True. ```python # Fetch specific link await book.fetch_link(Book.publisher) # Search by linked document fields (requires fetch_links=True) books = await Book.find( Book.author.name == "J.K. Rowling", fetch_links=True ).to_list() ``` -------------------------------- ### Perform simple update queries Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/update.md Apply simple updates like setting a field, incrementing a numeric field, or updating the current date directly on documents found via `find_one` or `find`. ```python bar = await Product.find_one(Product.name == "Mars") await bar.set({Product.name:"Gold bar"}) bar = await Product.find(Product.price > .5).inc({Product.price: 1}) ``` -------------------------------- ### Register a Synchronous After Event Action in Beanie Source: https://github.com/beanieodm/beanie/blob/main/docs/articles/1.8.0.md Use the `@after_event` decorator with an event type (e.g., `Replace`) to register a synchronous method that runs after a document event completes. This example decrements a number field after replacement. ```python from beanie import Insert, Replace class Sample(Document): num: int name: str @after_event(Replace) def num_change(self): self.num -= 1 ``` -------------------------------- ### Beanie State Management Operations Source: https://context7.com/beanieodm/beanie/llms.txt Demonstrates creating a document, checking for changes, modifying fields, saving only changes with `save_changes()`, and rolling back unsaved modifications using `rollback()`. ```python async def state_management_example(): # Create and insert item = Item(name="Widget", price=10.0, metadata={"color": "red"}) await item.insert() # Check if changed print(item.is_changed) # False # Make changes item.price = 12.0 item.metadata["size"] = "large" print(item.is_changed) # True print(item.get_changes()) # {'price': 12.0, 'metadata.size': 'large'} # Save only the changes (not full document) await item.save_changes() print(item.is_changed) # False # Rollback unsaved changes item.price = 100.0 item.rollback() print(item.price) # 12.0 # Check previous changes (if state_management_save_previous=True) item.price = 15.0 await item.save_changes() print(item.has_changed) # True print(item.get_previous_changes()) # {'price': 15.0} ``` -------------------------------- ### Control Nesting Depth for Nested Links Source: https://context7.com/beanieodm/beanie/llms.txt Demonstrates how to control the maximum levels of nested links to fetch using the nesting_depth parameter during a find operation. ```python # Control nesting depth for nested links books = await Book.find( fetch_links=True, nesting_depth=2 # Max levels to fetch ).to_list() ``` -------------------------------- ### Triggering Validation Error on Save Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/on_save_validation.md When `validate_on_save` is enabled, attempting to save a document with an invalid field type will raise an error. This example demonstrates assigning a wrong type to 'num' and then calling `replace()`, which will trigger the validation error. ```python sample = Sample.find_one(Sample.name == "Test") sample.num = "wrong value type" # Next call will raise an error await sample.replace() ``` -------------------------------- ### Define a View with Linked Documents Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/views.md Create a view that includes a `Link` field to another document. This requires defining the source document and the view with a pipeline that projects the necessary fields. ```python from beanie import Document, Link, View class Author(Document): name: str class BookView(View): title: str author: Link[Author] class Settings: source = Book pipeline = [ {" $project": {"title": 1, "author": 1}}, ] ``` -------------------------------- ### Implement Event Hooks for Document Actions Source: https://context7.com/beanieodm/beanie/llms.txt Utilize `@before_event` and `@after_event` decorators to define pre- and post-action hooks for document operations like Insert, Replace, Update, and Delete. Async hooks are supported. Actions can be skipped during operations. ```python from datetime import datetime, timezone from beanie import Document, Insert, Replace, Update, Delete, before_event, after_event class AuditedDocument(Document): name: str created_at: datetime | None = None updated_at: datetime | None = None version: int = 1 @before_event(Insert) def set_created_at(self): self.created_at = datetime.now(timezone.utc) self.updated_at = self.created_at @before_event(Replace, Update) def set_updated_at(self): self.updated_at = datetime.now(timezone.utc) @before_event(Update) def increment_version(self): self.version += 1 @after_event(Insert) async def notify_created(self): # Async hooks are supported print(f"Document {self.id} created") @after_event(Delete) async def cleanup(self): print(f"Document {self.id} deleted") async def hooks_example(): doc = AuditedDocument(name="Test") await doc.insert() # triggers set_created_at, notify_created doc.name = "Updated" await doc.save() # triggers set_updated_at await doc.set({AuditedDocument.name: "Changed"}) # triggers increment_version # Skip specific actions await doc.insert(skip_actions=['set_created_at']) await doc.replace(skip_actions=[After]) # Skip all after hooks ``` -------------------------------- ### Beanie Sync with Local Merge Strategy Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/find.md Employ `sync()` with `MergeStrategy.local` to merge database changes into the local document, preserving local modifications. Be aware that this can potentially raise an `ApplyChangesException` on conflict. ```python from beanie import MergeStrategy await bar.sync(merge_strategy=MergeStrategy.local) ``` -------------------------------- ### Run Single Backward Migration Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/migrations.md Reverts one migration. Use the --backward flag to run migrations in reverse. ```shell beanie migrate -uri 'mongodb+srv://user:pass@host' -db db -p relative/path/to/migrations/directory/ --distance 1 --backward ``` -------------------------------- ### Task with mixed dependency types Source: https://github.com/beanieodm/beanie/blob/main/docs/batteries/queue.md Configure a task to have multiple dependency links, each with a different dependency type (ALL_OF, ANY_OF, DIRECT). This allows for complex task orchestration. ```python class TaskWithMultipleDependencies(Task): s: str list_of_dependencies_all: Link[SimpleTask] = Field( dependency_type=DependencyType.ALL_OF ) list_of_dependencies_any: Link[SimpleTask] = Field( dependency_type=DependencyType.ANY_OF ) direct_dependency: Link[SimpleTask] = Field( dependency_type=DependencyType.DIRECT ) ``` -------------------------------- ### Fetch Links on Demand for a View Instance Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/views.md Fetch linked documents for an individual view instance after the initial query. Use `fetch_all_links()` on the view instance to resolve all `Link` fields. ```python book = await BookView.find_one(BookView.title == "Beanie Guide") await book.fetch_all_links() print(book.author.name) ``` -------------------------------- ### Simple Projections with Pydantic Model Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/find.md For simple projections, define a Pydantic model with the required fields and pass it to the `project()` method. This reduces database bandwidth and processing. ```python class ProductShortView(BaseModel): name: str price: float chocolates = await Product.find( Product.category.name == "Chocolate").project(ProductShortView).to_list() ``` -------------------------------- ### Save Document with Linked Documents (WriteRules.WRITE) Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/relations.md Saves a House document, inserting any new linked Window documents and updating the House document. Use WriteRules.WRITE to sync linked documents. ```python house.windows = [Window(x=100, y=100)] house.name = "NEW NAME" # The next call will insert a new window object and replace the house instance with updated data await house.save(link_rule=WriteRules.WRITE) ``` -------------------------------- ### Performing Bulk Updates and Finds Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/inheritance.md Standard operations like bulk updates and finding single documents work similarly to simple documents, even within an inheritance structure. Use the specific model class for these operations. ```python await Bike.find().update({"$set": {Bike.color: 'yellow'}}) ``` ```python await Car.find_one(Car.body == 'sedan') ``` -------------------------------- ### Insert a Single Document using Class Method Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/insert.md Alternatively, use the `insert_one()` class method on the Document model to insert a single instance. ```python await Product.insert_one(tonybar) ``` -------------------------------- ### Enable Previous State Tracking Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/state_management.md To also track previous changes saved in the database, set `state_management_save_previous = True` in addition to `use_state_management = True`. ```python class Sample(Document): num: int name: str class Settings: use_state_management = True state_management_save_previous = True ``` -------------------------------- ### Calculate Average Price with Search Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/aggregate.md Calculate the average price of products within a specific category using a search query. Requires the Product model to be defined. ```python avg_price = await Product.find( Product.category.name == "Chocolate" ).avg(Product.price) ``` -------------------------------- ### Enable State Management for Changes Source: https://github.com/beanieodm/beanie/blob/main/docs/articles/1.8.0.md To save only the fields that have changed since the document was loaded, set `use_state_management = True` in the `Settings` inner class. This optimizes updates by sending only modified data to the database. ```python class Sample(Document): num: int name: str class Settings: use_state_management = True ``` -------------------------------- ### Perform Basic Aggregations with Beanie Methods Source: https://context7.com/beanieodm/beanie/llms.txt Utilizes Beanie's built-in aggregation methods like avg, sum, min, max, and count for quick data analysis on Product documents. ```python from pydantic import BaseModel, Field from beanie import Document class Product(Document): name: str price: float category: str quantity: int async def aggregation_examples(): # Built-in aggregation methods avg_price = await Product.find( Product.category == "Chocolate" ).avg(Product.price) # Sum total_quantity = await Product.find().sum(Product.quantity) # Min/Max min_price = await Product.find().min(Product.price) max_price = await Product.find().max(Product.price) # Count count = await Product.find(Product.price < 5).count() # Aggregation over entire collection avg_all = await Product.avg(Product.price) ``` -------------------------------- ### Configure Cache Expiration and Capacity Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/cache.md Customize the cache behavior by setting `cache_expiration_time` (as a `timedelta`) and `cache_capacity` (maximum number of cached queries) in the `Settings` inner class. ```python class Sample(Document): num: int name: str class Settings: use_cache = True cache_expiration_time = datetime.timedelta(seconds=10) cache_capacity = 5 ``` -------------------------------- ### Paginate Documents with Skip and Limit Source: https://context7.com/beanieodm/beanie/llms.txt Implements pagination by skipping a specified number of documents and limiting the number of results returned. ```python # Skip and limit for pagination page = await Product.find( Product.in_stock == True ).skip(10).limit(10).to_list() ``` -------------------------------- ### Define List of Document Links Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/relations.md Defines a list of links from a House document to multiple Window documents. Each item in the list must be a Link to a Window document. ```python from typing import List from beanie import Document, Link class Window(Document): x: int = 10 y: int = 10 class House(Document): name: str door: Link[Door] windows: List[Link[Window]] ``` -------------------------------- ### Define Optional List of Document Links Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/relations.md Defines an optional list of links from a House document to multiple Yard documents. The list itself can be absent, or contain links to Yard documents. ```python from typing import List, Optional from beanie import Document, Link class Window(Document): x: int = 10 y: int = 10 class Yard(Document): v: int = 10 y: int = 10 class House(Document): name: str door: Link[Door] windows: List[Link[Window]] yards: Optional[List[Link[Yard]]] ``` -------------------------------- ### Define Multiple Indexes in Settings Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/defining-a-document.md Configure various types of indexes, including single fields, compound indexes with directions, and `IndexModel` instances, within the `Settings.indexes` list. ```python from typing import List from beanie import Document, IndexModel import pymongo # Assuming SubDocument is defined elsewhere # class SubDocument(BaseModel): # ... class DocumentTestModelWithIndex(Document): test_int: int test_list: List[SubDocument] test_str: str class Settings: indexes = [ "test_int", [ ("test_int", pymongo.ASCENDING), ("test_str", pymongo.DESCENDING), ], IndexModel( [("test_str", pymongo.DESCENDING)], name="test_string_index_DESCENDING", ), ] ``` -------------------------------- ### Run Single Forward Migration Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/migrations.md Executes one forward migration. Ensure your MongoDB is a replica set if using transactions (default). ```shell beanie migrate -uri 'mongodb+srv://user:pass@host' -db db -p relative/path/to/migrations/directory/ --distance 1 ``` -------------------------------- ### Fetch Linked Documents in a View Query Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/views.md When querying a view with `Link` fields, use `fetch_links=True` to automatically resolve the linked documents using `$lookup`. This ensures that the linked fields are populated with full document data. ```python # Find with automatic link resolution books = await BookView.find( BookView.title == "Beanie Guide", fetch_links=True, ).to_list() # author is now a full Author document, not a DBRef print(books[0].author.name) ``` -------------------------------- ### Registering Actions for Multiple Events Source: https://github.com/beanieodm/beanie/blob/main/docs/tutorial/actions.md A single method can be registered to trigger before multiple events by listing them as arguments to the `@before_event` decorator. This simplifies handling common pre-operation logic. ```python from beanie import Insert, Replace, before_event class Sample(Document): num: int name: str @before_event(Insert, Replace) def capitalize_name(self): self.name = self.name.capitalize() ```