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

序列化

在本指南中,您可以学习;了解如何使用PyMongo序列化您的自定义类型。

序列化是将Python对象映射到BSON文档以存储在MongoDB中的进程。 当您将文档插入集合时, PyMongo会自动将基本Python类型转换为BSON 。 同样,当您从集合中检索文档时, PyMongo会自动将返回的BSON转换回相应的Python类型。

有关 Python 到 BSON 映射的完整列表,请参阅 bson API 文档。

要序列化和反序列化自定义Python类,您必须实现自定义逻辑来处理转换。 以下部分介绍如何序列化和反序列化自定义类。

要序列化自定义类,必须将该类转换为字典。以下示例使用 vars() 方法序列化自定义类,然后将序列化对象插入到集合中。选择 SynchronousAsynchronous标签页以查看相应的代码:

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对象。选择SynchronousAsynchronous标签页以查看相应的代码:

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

在此页面上