Python mongodb批量修改数据库某个字段

数据库集合中有个字段是短信价格(单价*计费条数),经常会需要修改历史短信价格,由于数据量比较大(百万或者千万级别),for循环一条一条更新则速度非常慢。可使用下面脚本批量更新:

python 复制代码
from pymongo import MongoClient, UpdateOne

# ------------------ 配置 MongoDB ------------------
username = "xxxx"
password = "xxxx"
host = "172.16.xxx.xxx"
port = 27017
db_name = "sms"
collection_name = "sms_record"

client = MongoClient(
    host=host,
    port=port,
    username=username,
    password=password,
    authSource=db_name
)

db = client[db_name]
smsRecord = db[collection_name]

# ------------------ 查询条件 ------------------
startPt = "20260101"
endPt = "20260107"
appId = 123456
query = {"pt": {'$gte': startPt, "$lte": endPt}, "appId": appId}

# ------------------ 批量更新设置 ------------------
batch_size = 1000  # 每批处理多少条
operations = []
updated_count = 0
smsPrice = 0.03  # 标准单价

# ------------------ 遍历并准备批量操作 ------------------
for item in smsRecord.find(query, no_cursor_timeout=True):
    sid = item['sid']
    amount = item['amount']
    fee = item['fee']
    
    if float(fee) / float(amount) == smsPrice:
        continue  # 已是标准单价,不需要更新

    print(item)
    new_fee = smsPrice * amount
    operations.append(UpdateOne({'sid': sid}, {'$set': {'fee': new_fee}}))
    updated_count += 1

    # 达到批量大小就提交一次
    if len(operations) >= batch_size:
        smsRecord.bulk_write(operations)
        print(f"已更新 {updated_count} 条记录")
        operations = []

# ------------------ 提交剩余未提交的操作 ------------------
if operations:
    smsRecord.bulk_write(operations)
    print(f"已更新 {updated_count} 条记录")

print(f"批量更新完成,总共更新 {updated_count} 条记录")
相关推荐
PaperData2 分钟前
2003-2026.1北大法宝地方数字经济政策数据
数据库·数据分析·学习方法·经管
BU摆烂会噶8 分钟前
【LangGraph】持久化实现的三大能力——人机交互
数据库·人工智能·python·langchain·人机交互
.柒宇.22 分钟前
AI掘金头条项目部署实践指南
linux·运维·python·fastapi
WL_Aurora23 分钟前
Python 算法基础篇之树和二叉树
python·算法
jefl jxak25 分钟前
mysql用户名怎么看
数据库·mysql
unDl IONA30 分钟前
mysql之如何获知版本
数据库·mysql
小郑加油35 分钟前
python学习Day11:认识与创建CSV文件
开发语言·python·学习
Pkmer36 分钟前
Java程序员大战Python面向对象
python·ai编程
俺不要写代码41 分钟前
数据库:约束
数据库·mysql