pymongo提供一些常用的数据类型,如:数据、字符串、日期等。如果感觉还不能满足需求,那么还可以自定义数据类型。 首先定义一个类: class Custom(object): def __init__(self, x): self.__x = x def x(self): return self.__x 要将自定义类型的数据存入数
pymongo提供一些常用的数据类型,如:数据、字符串、日期等。如果感觉还不能满足需求,那么还可以自定义数据类型。
首先定义一个类:
class Custom(object): def __init__(self, x): self.__x = x def x(self): return self.__x
要将自定义类型的数据存入数据库中需要先进行编码;将数据从数据库读取出来后又需要再解码。
手动编码/解码
我们可以定义两个方法,在插入和查询数据时进行手动的编码、解码。
def encode_custom(custom): return {"_type": "custom", "x": custom.x()} def decode_custom(document): assert document["_type"] == "custom" return Custom(document["x"]) print(db.test.insert({"custom": encode_custom(Custom(5))})) print(db.test.find_one()['custom'])
自动编码/解码
手动地进行编码虽然可行,但是还是不太方便。我们还可以使用 SONManipulator 进行自动编码。
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 db.add_son_manipulator(Transform()) print(db.test.insert({"custom": Custom(5)})) print(db.test.find_one())
二进制编码
我们也可以将其编码成二进制进行存储。
from bson.binary import Binary def to_binary(custom): return Binary(str(custom.x()), 128) def from_binary(binary): return Custom(int(binary)) class TransformToBinary(SONManipulator): def transform_incoming(self, son, collection): for (key, value) in son.items(): if isinstance(value, Custom): son[key] = to_binary(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, Binary) and value.subtype == 128: son[key] = from_binary(value) elif isinstance(value, dict): son[key] = self.transform_outgoing(value, collection) return son db.add_son_manipulator(TransformToBinary()) print(db.test.insert({"custom": Custom(5)})) print(db.test.find_one())
原文地址:pymongo教程(3)——自定义数据类型, 感谢原作者分享。

mySqlStringTypesimpactStorageAndPerformanCeaseAsfollows:1)长度,始终使用theSamestoragespace,whatcanbefasterbutlessspace-felfficity.2)varCharisvariable varcharisvariable length,morespace-morespace-morespace-effficitybuteftife buteftife butfority butfority textifforlyslower.3)

mySqlStringTypesIncludeVarChar,文本,char,enum和set.1)varCharisVersAtileForvariable-lengthStringStringSuptOptoPeptoPepecifientlimit.2)textisidealforlargetStortStorStoverStorextorewiteWithoutAdefinedLengthl.3)charlisfixed-Length

MySQLoffersvariousstringdatatypes:1)CHARforfixed-lengthstrings,2)VARCHARforvariable-lengthtext,3)BINARYandVARBINARYforbinarydata,4)BLOBandTEXTforlargedata,and5)ENUMandSETforcontrolledinput.Eachtypehasspecificusesandperformancecharacteristics,sochoose

TograntpermissionstonewMySQLusers,followthesesteps:1)AccessMySQLasauserwithsufficientprivileges,2)CreateanewuserwiththeCREATEUSERcommand,3)UsetheGRANTcommandtospecifypermissionslikeSELECT,INSERT,UPDATE,orALLPRIVILEGESonspecificdatabasesortables,and4)

toadduserInmysqleffectection andsecrely,theTheSepsps:1)USEtheCreateuserStattoDaneWuser,指定thehostandastrongpassword.2)GrantNectalRevileSaryPrivilegesSustate,usiveleanttatement,AdheringTotheTeprinciplelastPrevilegege.3)

toaddanewuserwithcomplexpermissionsinmysql,loldtheSesteps:1)创建eTheEserWithCreateuser'newuser'newuser'@''localhost'Indedify'pa ssword';。2)GrantreadAccesstoalltablesin'mydatabase'withGrantSelectOnMyDatabase.to'newuser'@'localhost';。3)GrantWriteAccessto'

MySQL中的字符串数据类型包括CHAR、VARCHAR、BINARY、VARBINARY、BLOB、TEXT,排序规则(Collations)决定了字符串的比较和排序方式。1.CHAR适合固定长度字符串,VARCHAR适合可变长度字符串。2.BINARY和VARBINARY用于二进制数据,BLOB和TEXT用于大对象数据。3.排序规则如utf8mb4_unicode_ci忽略大小写,适合用户名;utf8mb4_bin区分大小写,适合需要精确比较的字段。

最佳的MySQLVARCHAR列长度选择应基于数据分析、考虑未来增长、评估性能影响及字符集需求。1)分析数据以确定典型长度;2)预留未来扩展空间;3)注意大长度对性能的影响;4)考虑字符集对存储的影响。通过这些步骤,可以优化数据库的效率和扩展性。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)