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を使用してカスタム型を直列化する方法を学習できます。

シリアル化は、 MongoDBにストレージためにPythonオブジェクトをBSONドキュメントにマッピングするプロセスです。 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

項目一覧