- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHPPhysics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to encode custom python objects as BSON with Pymongo?
使用 Pymongo 将自定义 Python 对象编码为 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 字段。
广告