PyMongo, Motor, Beanie

zz1·2024년 12월 13일

특징

  • PyMongo: MongoDB를 사용하기 위한 툴
  • Motor: MongoDB용 비동기 Python 드라이버
  • Beanie: MongoDB용 비동기 Python ODM(object-document mapper). 데이터 모델은 Pydantic을 기반으로 한다.

Motor: PyMongo와의 차이점

  • Motor는 MotorClient라는 단일 클라이언트 클래스를 제공한다. PyMongo MongoClient와 달리, Motor의 클라이언트 클래스는 인스턴스화가 될 때 백그라운드에서 연결을 시작하지 않는다. 작업을 처음 시도할 때 필요에 따라 연결한다.
  • Motor가 네트워크 I/O를 하는 방식은 coroutines다.
  • 멀티스레딩과 포킹은 지원되지 않는다.

Beanie

Defining a document

데이터베이스의 컬렉션과 상호작용하는 Document를 만들 수 있다. 이는 데이터베이스 스키마를 나타낸다. 컬렉션과 연결해주기 위해 Settings 서브클래스를 정의해야 한다.

from beanie import Document

class Product(Document):
	title: str
    price: str
    
    class Settings:
    	name = "products"

Initialization

  • Beanie는 Motor를 비동기 데이터베이스 엔진처럼 사용한다.
client = AsyncIOMotorClient('db_url')
await init_beanie(database=client.db_name, 
	  document_models=[Sample])
  • init_beanie: 2개의 매개변수를 가진다.
    - database: 사용될 데이터베이스 이름
    - document_models: 정의된 document 모델 리스트

Insert the documents

  • Beanie document는 pydantic 모델처럼 행동한다. 그러므로, 비슷한 방식으로 만들어질 수 있다.
class Product(Document):
	name:str
    price: Indexed(float)
    
    class Settings:
    	name = 'products'
 
firstProduct = Product(name="first", price=5)
secondProduct = Product(name="second", price=1)
  • document를 데이터베이스에 저장하기 위해서는 insert() create()를 부를 수 있다. save()의 경우 새 document에 대해서는 같게 동작하지만, 존재하는 document에 대해서는 업데이트를 한다.
await firstProduct.insert()
await secondProduct.create()
await Product.insert_many([firstProduct, secondProduct])

Finding documents

// 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 초기화
  • 인스턴스의 메서드(ex. create())는 모델의 Settings subclass의 내용을 바탕으로 컬렉션을 결정

참고

0개의 댓글