MongoDB.local SF, Jan 15: See the speaker lineup & ship your AI vision faster. Use WEB50 to save 50%
Find out more >
Docs Menu
Docs Home
/ /

직렬화

이 가이드 에서는 PyMongo 사용하여 사용자 지정 유형을 직렬화하는 방법을 학습 수 있습니다.

직렬화 는 Python 객체 BSON 문서 에 매핑하여 MongoDB 에 저장 프로세스 입니다. PyMongo 문서 를 컬렉션 에 삽입할 때 기본 Python 유형을 BSON 으로 자동 변환합니다. 마찬가지로, 컬렉션 에서 문서 조회 때 PyMongo 반환된 BSON 해당 Python 유형으로 다시 자동으로 변환합니다.

Python- BSON 매핑의 전체 목록은bson API 문서를 참조하세요.

사용자 지정 Python 클래스를 직렬화 및 역직렬화하려면 변환을 처리하다 사용자 지정 로직을 구현 해야 합니다. 다음 섹션에서는 사용자 지정 클래스를 직렬화 및 역직렬화하는 방법을 보여 줍니다.

사용자 지정 클래스를 직렬화하려면 클래스를 딕셔너리로 변환해야 합니다. 다음 예시 vars() 메서드를 사용하여 사용자 지정 클래스를 직렬화한 다음 직렬화된 객체 컬렉션 에 삽입합니다. Synchronous 또는 Asynchronous 탭 선택하여 해당 코드를 확인합니다.

class Restaurant:
def __init__(self, name, cuisine):
self.name = name
self.cuisine = cuisine
restaurant = Restaurant("Example Cafe", "Coffee")
restaurant_dict = vars(restaurant)
collection.insert_one(restaurant_dict)
class Restaurant:
def __init__(self, name, cuisine):
self.name = name
self.cuisine = cuisine
restaurant = Restaurant("Example Cafe", "Coffee")
restaurant_dict = vars(restaurant)
await collection.insert_one(restaurant_dict)

앞의 예시 Restaurant 객체 다음 사전으로 직렬화합니다.

{'name': 'Example Cafe', 'cuisine': 'Coffee'}

컬렉션 에 문서를 삽입하는 방법에 학습 보려면 문서 삽입 가이드 를 참조하세요.

사용자 지정 클래스를 역직렬화하려면 딕셔너리를 클래스의 인스턴스 로 다시 변환해야 합니다. 다음 예시 에서는 컬렉션 에서 문서 검색한 다음 이전 예시 의 Restaurant 객체 로 다시 변환합니다. Synchronous 또는 Asynchronous 탭 선택하여 해당 코드를 확인합니다.

def deserialize_restaurant(doc):
return Restaurant(name=doc["name"], cuisine=doc["cuisine"])
restaurant_doc = collection.find_one({"name": "Example Cafe"})
restaurant = deserialize_restaurant(restaurant_doc)
def deserialize_restaurant(doc):
return Restaurant(name=doc["name"], cuisine=doc["cuisine"])
restaurant_doc = await collection.find_one({"name": "Example Cafe"})
restaurant = deserialize_restaurant(restaurant_doc)

컬렉션 에서 문서를 검색하는 방법에 대해 자세히 학습 문서 찾기 가이드 참조하세요.

돌아가기

확장 JSON

이 페이지의 내용