pymongo 批量插入数据

在使用pymongo的insert_many批量插入数据时遇到错误,原因是所有插入值相同。问题出在创建字典列表时,由于Python的引用特性,所有字典引用了同一内存地址。通过使用`copy()`方法创建字典副本,避免了值的同步,成功实现批量插入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pymongo 批量插入数据

使用python+mongodb开发一个简单的计算机运行情况监控程序,为了方便后期测试,打算模拟批量往mongodb中插入测试数据,在使用insert_many时出现,如下错误提示:

pymongo.errors.BulkWriteError: batch op errors occurred:

经过查资料发现是pymongo在处理批量插入时会检测值是否一致,如果所有的值都一样,就会报错,为此重新看代码,在代码中加入print函数,发现使用字典生成列表时,出现列表内的字典内容全部一样,代码如下:

def funInsert():
    DictMonitorList = []
        i = 0
        while i < 10:
            DictMonitor['host'] = '192.168.1.' + str(randint(1, 10)) 
            DictMonitor['boot_start'] = randint(1000,20000)
            DictMonitor['cpu_usage'] = randint(1,100)
            DictMonitor['ram'] = 80123
            DictMonitorList.append(DictMonitor)
            print(DictMonitorList)
    result = tblmonitor.insert_many(DictMonitorList)
    print(result)

输出结果如下:

[{'host': '192.168.1.7', 'boot_start': 14773, 'cpu_usage': 68, 'ram': 80123}]
插入成功0条
[{'host': '192.168.1.6', 'boot_start': 2069, 'cpu_usage': 96, 'ram': 80123}, {'host': '192.168.1.6', 'boot_start': 2069, 'cpu_usage': 96, 'ram': 80123}]
插入成功1条
[{'host': '192.168.1.5', 'boot_start': 18948, 'cpu_usage': 52, 'ram': 80123}, {'host': '192.168.1.5', 'boot_start': 18948, 'cpu_usage': 52, 'ram': 80123}, {'host': '192.168.1.5', 'boot_start': 18948, 'cpu_usage': 52, 'ram': 80123}]
插入成功2条
[{'host': '192.168.1.9', 'boot_start': 10814, 'cpu_usage': 56, 'ram': 80123}, {'host': '192.168.1.9', 'boot_start': 10814, 'cpu_usage': 56, 'ram': 80123}, {'host': '192.168.1.9', 'boot_start': 10814, 'cpu_usage': 56, 'ram': 80123}, {'host': '192.168.1.9', 'boot_start': 10814, 'cpu_usage': 56, 'ram': 80123}]
插入成功3条
[{'host': '192.168.1.7', 'boot_start': 13935, 'cpu_usage': 35, 'ram': 80123}, {'host': '192.168.1.7', 'boot_start': 13935, 'cpu_usage': 35, 'ram': 80123}, {'host': '192.168.1.7', 'boot_start': 13935, 'cpu_usage': 35, 'ram': 80123}, {'host': '192.168.1.7', 'boot_start': 13935, 'cpu_usage': 35, 'ram': 80123}, {'host': '192.168.1.7', 'boot_start': 13935, 'cpu_usage': 35, 'ram': 801
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值