(mongoDB and Python) AttributeError: 'InsertManyResult' object has no attribute 'inserted_count'

I follow the manual https://api.mongodb.com/python/3.4.0/api/pymongo/results.html
and similar problem python - AttributeError: 'dict' object has no attribute 'is_active' (PyMongo And Flask) - Stack Overflow (not fit mine issue)
after successfully .insert_many or .insert_one,
the .inserted_count not working

  • function main part I stock
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.")
  • output:
<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'

  • the whole code(incase someone want to take a look):
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))

If you read correctly

you will see that the return type of insert_many is of type pymongo.results.InsertManyResult which has the attributes:

  1. acknowledged

Is this the result of an acknowledged write operation?

The acknowledged attribute will be False when using WriteConcern(w=0) , otherwise True .

and

  1. inserted_ids

A list of _ids of the inserted documents, in the order provided.

There is no attribute named inserted_count, hence the error

The attribute inserted_count is only present in pymongo.results.BulkWriteResult.

I can use for InsertManyResult , instead of inserted_count that len(result.inserted_ids) is proper, which I learn from expert.

so the overall corrected code look like this:

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)


insert_one_or_many = input("U are Insert one or many values? (ex:1 for many , 0 for one): ")
newvalues_str = input("Enter new values: ")

one_or_many_bool = bool(int(insert_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_ids)
print(len(x.inserted_ids), "documents insert.")

number_of_insert_data = int(len(x.inserted_ids))

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))

thanks @steevej, ur suggestion looks really greate, and one more question , is there a manul, can list up all the calls ? That I’m working on Pymongo to MongoDB’s (Insert , Update, Query, Delete), so far I have known for “counting resluts” for Insert = len(result.inserted_ids) ; Update = x.modified_count , I might need a manul to know the rest , I wanna know how to count Query, Delete

Yes, a manual is always useful.

But it is really funny that you ask, because the manual is exactly the link you shared in your first post:

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.