From pymongo.mongo_client import mongoclientclient=mongoclient (' 192.168.30.252 ', 27017) client=drop_database (' Custom_type_example ') Db=client.custom_type_exampleclass custom (object):d EF __init__ (self,x): Self.__x=xdef x (self) : Return self.__x## #上面的类 cannot be automatically encoded by manual encoding as follows # to encode custom into JSON format def encode_custom (custom): return {"_type": "Custom", "X": Custom.x ()} #将document还原成custom类def Decode_custom (document): Assert document["_type"] = = "Custom" Return custom ( document["x"]) Db.test.insert ({"Custom": Encode_custom (Custom (5))}) Db.test.find_one () Decode_custom (db.test.find_ One () ["Custom"]) Decode_custom (Db.test.find_one () ["Custom"]). X () Foo=custom () foo.x () #手动显得繁琐, use automatic bar from Pymongo.son_manipulator Import Sonmanipulatorclass Transform (sonmanipulator):d ef transform_incoming (self, son, Collection): For (key, value) in Son.items (): If Isinstance (value, Custom): Son[key] = Encode_custom (value) elif is Instance (value, dict): # Make sure we recurse into sub-docs son[key] = self.transform_incoming (value, collection) return sondef transform_outgoing (self, Son, collection): For (key, value) in Son.items (): If Isinstance (value, D ICT): 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# join the manipulator into the database db.ad D_son_manipulator (Transform ()) #插入对象类型db. Test.insert ({"Custom": Custom (5)}) Db.test.find_one () #使用对象类型db. Test.find _one () ["Custom"].x () 5def to_binary (custom): Return binary (str (custom.x ()), +) def from_binary (binary): Return custom (binary) #二进制编码from bson.binary import binaryfrom pymongo.son_manipulator import Sonmanipulatorclass Transformtobinary (sonmanipulator):d ef transform_incoming (self, Son, collection): For (key, value) in Son.items (): If I Sinstance (value, Custom): Son[key] = to_binary (value) elif isinstance (value, dict): son[key] = Self.transform _incoming (value, collection) return Sondef Transform_outgoing (self, Son, collection): For (key, value) in Son.items (): If Isinstance (value, Binary) and Value.subtype = = 128: Son[key] = from_binary (value) elif isinstance (value, dict): Son[key] = self.transform_outgoing (value, Collectio N) return son# join binary operator Db.add_son_manipulator (transformtobinary ())
Python operation MongoDB Six custom type storage