序列化
Overview
在本指南中,您可以学习;了解如何使用PyMongo执行序列化。
序列化是将Python对象映射到BSON文档以存储在MongoDB中的进程。 当您将文档插入集合时, PyMongo会自动将基本Python类型转换为BSON 。 同样,当您从集合中检索文档时, PyMongo会自动将返回的BSON转换回相应的Python类型。
您可以使用PyMongo对以下Python类型进行序列化和反序列化:
str
int
float
bool
datetime.datetime
list
dict
None
有关 Python 到BSON映射的完整列表,请参阅 bson API文档。
自定义类
要序列化和反序列化自定义Python类,您必须实现自定义逻辑来处理转换。 以下部分介绍如何序列化和反序列化自定义类。
序列化自定义类
要序列化自定义类,必须将该类转换为字典。 以下示例使用 vars()
方法序列化自定义类,然后将序列化对象插入到集合中:
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)
前面的示例将 Restaurant
对象序列化到以下字典中:
{'name': 'Example Cafe', 'cuisine': 'Coffee'}
要学习;了解有关在集合中插入文档的更多信息,请参阅插入文档指南。
反序列化自定义类
要反序列化自定义类,必须将字典转换回该类的实例。 以下示例从集合中检索文档,然后将其转换回上一示例中的 Restaurant
对象:
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)
二进制数据
在所有版本的Python中, PyMongo将 bytes 类的实例编码为具有子类型 0 的二进制数据,这是二进制数据的默认子类型。在Python 3 中, PyMongo将这些值解码为 bytes
类的实例。在 Python 2 中,驾驶员将它们解码为具有子类型 0 的 Binary 类的实例。
以下代码示例展示了PyMongo如何解码 bytes
类的实例。选择 Python 2 或 Python 3标签页以查看相应的代码。
from pymongo import MongoClient client = MongoClient() client.test.test.insert_one({'binary': b'this is a byte string'}) doc = client.test.test.find_one() print(doc)
{u'_id': ObjectId('67afb78298f604a28f0247b4'), u'binary': Binary('this is a byte string', 0)}
from pymongo import MongoClient client = MongoClient() client.test.test.insert_one({'binary': b'this is a byte string'}) doc = client.test.test.find_one() print(doc)
{'_id': ObjectId('67afb78298f604a28f0247b4'), 'binary': b'this is a byte string'}