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