使用pymongo将自定义python对象编码为BSON

Leo*_*opd 7 python numpy bson pymongo

有没有办法告诉pymongo使用自定义编码器将python对象转换为BSON?

具体来说,我需要将numpy数组转换为BSON.我知道我可以手动确保每个numpy数组在发送到pymongo之前转换为本机python数组.但这是重复且容易出错的.我宁愿有办法设置我的pymongo连接来自动执行此操作.

muu*_*ope 2

你需要写一个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
Run Code Online (Sandbox Code Playgroud)

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

db.add_son_manipulator(Transform())
Run Code Online (Sandbox Code Playgroud)

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

  • `son_manipulator` 目前已被弃用。它们将在 v4.0 中被删除。官方建议是在将文档传递给 pymongo 之前对其进行转换,如 [docs](https://api.mongodb.com/python/current/api/pymongo/son_manipulator.html) 中所述 (3认同)