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

如何用Python删除MongoDB所有文档id_number字段最后四位字符?

Python实现MongoDB批量截断id_number字段最后四位字符

要批量修改集合中所有文档的id_number字段,去掉最后四位字符,可以结合MongoDB的聚合表达式和update_many方法实现,具体代码如下:

from pymongo import MongoClient

# 连接MongoDB服务(根据实际地址调整)
client = MongoClient('mongodb://localhost:27017/')
# 切换到目标数据库和集合
db = client['你的数据库名']
company_collection = db['你的集合名']

# 执行批量更新
update_result = company_collection.update_many(
    {},  # 空查询条件匹配所有文档
    [
        {
            "$set": {
                "id_number": {
                    # 截取从开头到长度减4的位置,去掉最后四位
                    "$substrCP": [
                        "$id_number",
                        0,
                        {"$subtract": [{"$strLenCP": "$id_number"}, 4]}
                    ]
                }
            }
        }
    ]
)

print(f"共更新 {update_result.modified_count} 条文档")

关键说明

  • 使用聚合管道式更新(MongoDB 4.2+支持):这种方式直接在数据库端完成字段计算,比查询后循环更新效率高得多
  • $strLenCP:获取id_number的字符长度(支持Unicode字符)
  • $subtract:用总长度减去4,得到需要保留的字符长度
  • $substrCP:从索引0开始截取指定长度的字符串,实现截断最后四位

可选优化

如果需要避免处理长度不足4的id_number字段,可以在查询条件中添加过滤规则:

update_result = company_collection.update_many(
    {
        "id_number": {
            "$type": "string",  # 确保字段是字符串类型
            "$regex": ".{4,}"   # 确保字符串长度≥4
        }
    },
    # 更新管道同上
    [
        {
            "$set": {
                "id_number": {
                    "$substrCP": ["$id_number", 0, {"$subtract": [{"$strLenCP": "$id_number"}, 4]}]
                }
            }
        }
    ]
)

注意事项

  • 操作前建议先备份数据,或用find_one_and_update测试单条文档的更新效果
  • 替换代码中的你的数据库名和你的集合名为实际名称

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 20:50:53