我遵循手册https://api.mongodb.com/python/3.4.0/api/pymongo/results.html
和类似问题AttributeError:';dict';对象没有属性';is_active';(PyMongo And Flask((不适合我的问题(
成功.insert_many
或.insert_one
后,.inserted_count
不工作
- 功能主要部分I库存
if one_or_many_bool == True:
x = mycol.insert_many(insert_values_json)
else:
x = mycol.insert_one(insert_values_json)
return x
print(x)
print(x.inserted_count, "documents insert.")
- 输出:
<pymongo.results.InsertManyResult object at 0x0000017D1D256950>
Traceback (most recent call last):
File "C:UserschuanOneDriveDesktop10.17_connect_mongoD_練習fake02.py", line 54, in <module>
print(x.inserted_count, "documents inserted.")
AttributeError: 'InsertManyResult' object has no attribute 'inserted_count'
- 整个代码(如果有人想看一看(:
import pymongo
import datetime
import json
from bson.objectid import ObjectId
from bson import json_util
def init_db(ip, db, coll):
try:
myclient = pymongo.MongoClient('mongodb://' + ip + '/')
mydb = myclient[db]
mycol = mydb[coll]
except Exception as e:
msg_fail_reason = "error in init_db function"
return msg_fail_reason
return mydb, mycol
# ins_data = insert_db_data
# one_or_many_bool: input 1 means True; input 0 is False
def ins_data(one_or_many_bool, insert_values_json ):
try:
if one_or_many_bool:
x = mycol.insert_many(insert_values_json)
else:
x = mycol.insert_one(insert_values_json)
return x
except Exception as e:
msg_fail_reason = "error in ins_data function"
return msg_fail_reason
msg_fail_reason = "no error occur"
ip_input = input("Enter the ip: ")
exist_DB_name = input("Enter exist DB name: ")
exist_coll_name = input("Enter exist collection name: ")
mydb, mycol = init_db(ip_input, exist_DB_name, exist_coll_name)
update_one_or_many = input("U are update one or many values? (ex:1 for many , 0 for one): ")
newvalues_str = input("Enter new values: ")
one_or_many_bool = bool(int(update_one_or_many))
insert_values_json =json.loads(newvalues_str)
x = ins_data(one_or_many_bool, insert_values_json )
print(x)
print(x.inserted_count, "documents insert.")
number_of_insert_data = int(x.inserted_count)
modified_data_list = []
for modified_data in mycol.find().sort("_id", -1).limit(number_of_insert_data):
# print(modified_data)
modified_data_list.append(modified_data)
def parse_json(data):
return json.loads(json_util.dumps(data))
# if someone want data in json
modified_data_json = parse_json(modified_data_list)
# 1 means success
return_status_str = { "ok" : 1 , "msg" : msg_fail_reason , "count" : number_of_insert_data}
print(return_status_str)
print(type(return_status_str))
正如PyMongo文档所描述的,InsertManyResult
没有inserted_count
属性。您可以改用len(result.inserted_ids)
。