____tz_zs
在使用 python 往 mongo 中存储数据时,抛出OverflowError: MongoDB can only handle up to 8-byte ints
错误。
from pymongo import MongoClient
# 地址,端口
mongo_client = MongoClient("ip", <端口号>) # 创建 MongoClient 对象
mongo_db = mongo_client["数据库名"] # MongoDB 中可存在多个数据库,根据数据库名称获取数据库对象(Database)
mongo_db.authenticate("用户", "密码") # 登录认证
record = {
"_id": "long_int_test",
"int": 11111111111111111111111111111111111111111111111111
}
res = mongo_db["test_table"].replace_one(filter={
"_id": record["_id"]}, replacement=record, upsert=True)
print(res)
"""
OverflowError: MongoDB can only handle up to 8-byte ints
"""
这是因为 python 的 int 类型是长整型,可以在计算中处理任意大的整数。而 MongoDB 的原生二进制扩展 JSON 格式/数据类型 —— 仅支持 32 位(有符号)和 64 位(有符号)整数 —— 8 字节为 64 位。
所以可以存储在 64 位 int 中的最大整数值是:
9,223,372,036,854,775,807
- | - | - |
---|---|---|
Int32 | 有符号32位整数 | -2147483648-2147483647 |
UInt32 | 无符号32位整数 | 0~4294967295 |
Int64 | 有符号64位整数 | -9223372036854775808~9223372036854775807 |
UInt64 | 无符号64位整数 | 0~18446744073709551615 |
参考:
OverflowError: MongoDB can only handle up to 8-byte ints?