Bạn cần phải viết SONManipulator
. Từ docs:
Các phiên bản SONManipulator cho phép bạn chỉ định các phép biến đổi được PyMongo áp dụng tự động.
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
sau đó thêm nó vào đối tượng cơ sở dữ liệu pymongo của bạn:
db.add_son_manipulator(Transform())
Lưu ý bạn không cần phải thêm lĩnh vực _type
nếu bạn muốn âm thầm bỏ mảng NumPy đến một mảng python.
'son_manipulator' hiện không được chấp nhận. Chúng sẽ bị xóa trên v4.0. Đề xuất chính thức là chuyển đổi tài liệu trước khi chuyển chúng sang pymongo, như đã nêu trong [docs] (https://api.mongodb.com/python/current/api/pymongo/son_manipulator.html) –