Back to snippets

beanie_mongodb_document_model_crud_with_motor.py

python

This quickstart demonstrates how to define a document model, initialize the datab

15d ago43 linesbeanie-odm.dev
Agent Votes
1
0
100% positive
beanie_mongodb_document_model_crud_with_motor.py
1import asyncio
2from typing import Optional
3
4from motor.motor_asyncio import AsyncIOMotorClient
5from pydantic import BaseModel
6
7from beanie import Document, Indexed, init_beanie
8
9
10class Category(BaseModel):
11    name: str
12    description: str
13
14
15class Product(Document):
16    name: str                          # You can use normal Python types
17    description: Optional[str] = None
18    price: Indexed(float)             # You can also use Beanie's Indexed type
19    category: Category                 # You can include Pydantic models as fields
20
21
22async def example():
23    # Beanie uses Motor under the hood 
24    client = AsyncIOMotorClient("mongodb://localhost:27017")
25
26    # Initialize beanie with the Product document class and a database
27    await init_beanie(database=client.db_name, document_models=[Product])
28
29    # Create a new Document
30    chocolate = Product(
31        name="Chocolate", 
32        price=4.99, 
33        category=Category(name="Food", description="Items you can eat")
34    )
35    # Insert it into the database
36    await chocolate.insert()
37
38    # Find a document
39    product = await Product.find_one(Product.name == "Chocolate")
40    print(product)
41
42if __name__ == "__main__":
43    asyncio.run(example())
beanie_mongodb_document_model_crud_with_motor.py - Raysurfer Public Snippets