MotorClient라는 단일 클라이언트 클래스를 제공한다. PyMongo MongoClient와 달리, Motor의 클라이언트 클래스는 인스턴스화가 될 때 백그라운드에서 연결을 시작하지 않는다. 작업을 처음 시도할 때 필요에 따라 연결한다.데이터베이스의 컬렉션과 상호작용하는 Document를 만들 수 있다. 이는 데이터베이스 스키마를 나타낸다. 컬렉션과 연결해주기 위해 Settings 서브클래스를 정의해야 한다.
from beanie import Document
class Product(Document):
title: str
price: str
class Settings:
name = "products"
client = AsyncIOMotorClient('db_url')
await init_beanie(database=client.db_name,
document_models=[Sample])
init_beanie: 2개의 매개변수를 가진다.database: 사용될 데이터베이스 이름document_models: 정의된 document 모델 리스트class Product(Document):
name:str
price: Indexed(float)
class Settings:
name = 'products'
firstProduct = Product(name="first", price=5)
secondProduct = Product(name="second", price=1)
insert() create()를 부를 수 있다. save()의 경우 새 document에 대해서는 같게 동작하지만, 존재하는 document에 대해서는 업데이트를 한다.await firstProduct.insert()
await secondProduct.create()
await Product.insert_many([firstProduct, secondProduct])
// this returns a FindMany object
findresult = Product.find(search_criteria)
// search
products = await Product.find(Product.price<10).to_list()
AsyncIOMotorClient는 MongoDB에 대한 단일 연결을 만든다.init_beanie로 Beanie 초기화create())는 모델의 Settings subclass의 내용을 바탕으로 컬렉션을 결정