如何使用 Pymongo 将自定义 Python 对象编码为 BSON?

pythonserver side programmingprogramming

要使用 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): # 确保我们递归到子文档
        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] = decrypt_custom(value)
        else: # 再次确保递归到子文档
          son[key] = self.transform_outgoing(value, collection)
    return son

然后将其添加到您的 pymongo 数据库对象 −

db.add_son_manipulator(Transform())

请注意,如果您想将 numpy 数组默默转换为 python 数组,则不必添加 _type 字段。


相关文章


有用资源