如何使用Pymongo将自定义python对象编码为BSON?
要将自定义python对象编码为Pymongo的BSON,必须编写SONManipulator。从文档:
SONManipulator实例允许您指定要由PyMongo自动应用的转换。
from pymongo.son_manipulator import SONManipulator
class Transform(SONManipulator):
def transform_incoming(self, son, collection):
for (key, value) in son.items():
if isinstance(value, Custom):
son[key] = encode_custom(value)
elif isinstance(value, dict): # Make sure we recurse into sub-docs
son[key] = self.transform_incoming(value, collection)
return son
def transform_outgoing(self, son, collection):
for (key, value) in son.items():
if isinstance(value, dict):
if "_type" in value and value["_type"] == "custom":
son[key] = decode_custom(value)
else: # Again, make sure to recurse into sub-docs
son[key] = self.transform_outgoing(value, collection)
return son然后将其添加到您的pymongo数据库对象-
db.add_son_manipulator(Transform())
请注意,如果要将静默的numpy数组强制转换为python数组,则不必添加_type字段。
热门推荐
10 祝老婆生日祝福语简短
11 祝贺开业文案祝福语简短
12 生日祝福语 简短独特老弟
13 生病祝福语简短文案
14 祝妹妹毕业祝福语简短
15 祝福语大全简短赞美同学
16 酒桌升学祝福语简短
17 双节祝福语简短唯美
18 求简短的职场祝福语