You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用pymongo更新MongoDB集合所有文档的字段类型

解决方案

整数字段转换为int类型

你之前的代码错误是因为类型转换逻辑在Python本地执行,无法直接引用MongoDB文档内的字段值,可通过MongoDB 4.2及以上版本支持的更新聚合管道实现批量转换,直接在数据库层读取字段值完成类型修改,代码如下:

import pymongo
from pymongo import MongoClient

# 连接数据库逻辑(可复用你现有代码)
client = MongoClient("你的MongoDB连接串")
db = client["你的数据库名"]
our_collection = db["our_coll_name"]

# 批量转换整数字段
our_collection.update_many(
    {}, # 匹配集合内所有文档
    [
        {
            "$set": {
                "fga": {"$toInt": "$fga"},
                "fgm": {"$toInt": "$fgm"}
            }
        }
    ]
)

如果你使用的MongoDB版本低于4.2,可遍历文档逐个更新:

for doc in our_collection.find({}, ["fga", "fgm"]):
    our_collection.update_one(
        {"_id": doc["_id"]},
        {
            "$set": {
                "fga": int(doc["fga"]),
                "fgm": int(doc["fgm"])
            }
        }
    )

日期字段转换为MongoDB专属Date类型

MongoDB内置Date类型,底层存储为UTC时间戳,支持日期范围查询、时区转换等操作,可直接适配gameTime、gameDate、updated三个字段,转换代码可和整数转换合并:

our_collection.update_many(
    {},
    [
        {
            "$set": {
                # 整数字段转换
                "fga": {"$toInt": "$fga"},
                "fgm": {"$toInt": "$fgm"},
                # 日期字段转换,$toDate可自动识别你数据中的标准UTC时间字符串
                "gameTime": {"$toDate": "$gameTime"},
                "gameDate": {"$toDate": "$gameDate"},
                "updated": {"$toDate": "$updated"}
            }
        }
    ]
)

转换完成后,用pymongo读取时这些字段会自动映射为Python的datetime.datetime类型,默认保留UTC时区。如果存在部分文档缺失对应字段的场景,可搭配$ifNull运算符设置默认值,避免转换报错:
示例:"fga": {"$toInt": {"$ifNull": ["$fga", 0]}} 表示fga字段缺失时默认转换为0。

内容的提问来源于stack exchange,提问作者Canovice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 04:33:02