如何在 Pymongo 中將自定義 python 物件編碼為 BSON?


要在 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 欄位。

更新於: 2020 年 6 月 16 日

335 次閱讀

開啟您的 職業生涯

完成課程並獲得認證

開始瞭解
廣告
© . All rights reserved.