专业编程基础技术教程

网站首页 > 基础教程 正文

mongodb 数据更新性能分析_mongodb怎样更新一条数据

ccvgpt 2025-02-21 12:24:54 基础教程 36 ℃

之前的start_time字段是 datetime 类型,后来改成 int 类型的时间戳,因此,需要刷数据库。简单分析一下,update_onebulk_write 的性能差异,测试发现 bulk_write 速度是 update_one 的40倍。此外,mongodb 数据库创建索引,查询更快哦。

  • 7千数据,bulk_write 批量更新耗时7秒,update_one 逐个更新耗时 267秒,相差38倍
  • 3万数据,bulk_write 批量更新耗时33秒,update_one 逐个更新耗时 1214秒,相差37倍

ailx10

mongodb 数据更新性能分析_mongodb怎样更新一条数据

1952 次咨询

4.9

网络安全优秀回答者

互联网行业 安全攻防员

去咨询

逐个更新 start_time 字段,从 datetime 类型转为 int 类型

from pymongo import MongoClient
from datetime import datetime

# 连接到 MongoDB
client = MongoClient('mongodb://localhost:27017/')
db = client.mydatabase  
collection = db.collectionName 

# 更新文档中的 start_time 字段
for doc in collection.find({"start_time": {"$exists": True}}):
    start_time = doc.get("start_time")
    if isinstance(start_time, datetime):
        # 如果 start_time 是 datetime.datetime 对象,则将其转换为时间戳(毫秒级)
        start_time_timestamp = int(start_time.timestamp() * 1000)
        # 更新文档中的 start_time 字段为时间戳格式(NumberLong格式)
        collection.update_one({"_id": doc["_id"]}, {"$set": {"start_time": start_time_timestamp}})

批量更新 start_time 字段,从 datetime 类型转为 int 类型

from pymongo import MongoClient
from datetime import datetime
from pymongo import UpdateOne

# 连接到 MongoDB
client = MongoClient('mongodb://localhost:27017/')
db = client.mydatabase  
collection = db.collectionName 

# 创建批量更新操作列表
bulk_operations = []

# 更新文档中的 start_time 字段
for doc in collection.find({"start_time": {"$exists": True}}):
    start_time = doc.get("start_time")
    if isinstance(start_time, datetime):
        # 如果 start_time 是 datetime.datetime 对象,则将其转换为时间戳(毫秒级)
        start_time_timestamp = int(start_time.timestamp() * 1000)
        # 构造更新操作
        update_operation = UpdateOne({"_id": doc["_id"]}, {"$set": {"start_time": start_time_timestamp}})
        # 添加更新操作到批量更新操作列表中
        bulk_operations.append(update_operation)

# 执行批量更新操作
if bulk_operations:
    collection.bulk_write(bulk_operations)

创建索引,有助于提高性能

from pymongo import MongoClient

# 连接到 MongoDB
client = MongoClient('mongodb://localhost:27017/')
db = client.mydatabase
collection = db.collectionName

# 添加字段的索引
collection.create_index([("field_name", 1)])  # 1 表示升序索引,-1 表示降序索引

发布于 2024-04-03 17:42?IP 属地北京

最近发表
标签列表