I follow the manual https://api.mongodb.com/python/3.4.0/api/pymongo/results.html
and similar problem AttributeError: 'dict' object has no attribute 'is_active' (PyMongo And Flask) (not fit mine issue)
after successfully .insert_many
or .insert_one
,
the .inserted_count
not working
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:\Users\chuan\OneDrive\Desktop\10.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))
As the PyMongo doc described, InsertManyResult
doesn't has the inserted_count
attrbute. You can use len(result.inserted_ids)
instead.