Counting number of documents inserted or upserted via PyMongo

I want to return Json result like below,
contains is it fuccessfully functioning (use 0/1) , modified contents and modified data count

Json result:

{“ok” : 1, “msg” : [{ “name” : “Moma”, “Age” : 33} , { “name” :
“Kara”, “Age” : 44} ], “count”: 2 }

The tried code below:
I tried to use .inserted_count and .upserted_count to count the number modified
and x_new = json.dumps(x) should transfer data into Json

seems I kind of know most logic, but not sure how to make logic work

import pymongo
import datetime
import json

def init_db(ip, db, coll):
    try:
        myclient = pymongo.MongoClient('mongodb://' + ip + '/')
        mydb = myclient[db]
        mycol = mydb[coll]
        success_condition = "success on initializ operation"

    except Exception as e: 
        success_condition = "failed on initializ operation"
        
    return mydb, mycol, success_condition

  # ins_data = insert_db_data
def ins_data(one_or_many_bool, insert_values_json):
    try:    
        if one_or_many_bool == True:
            x = mycol.insert_many(insert_values_json)
        else:
            x = mycol.insert_one(insert_values_json)

        success_condition_insert = "success on ins_data operation"

    except Exception as e: 
        success_condition_insert = "failed on ins_data operation"

    return x , success_condition_insert

ip_input = input("Enter the ip: ")
exist_DB_name = input("Enter exist DB name: ")
exist_coll_name = input("Enter exist collection name: ")
mydb, mycol, success_condition  = init_db(ip_input, exist_DB_name, exist_coll_name)
print(success_condition)

insert_one_or_many = input("U are update one or many values? ( 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 , success_condition_insert = ins_data(one_or_many_bool, insert_values_json)
print(success_condition_insert)
x_new = json.dumps(x)
print(x_new)
print(type(x_new))
  • the tried code output:
Traceback (most recent call last):
  File "C:\Users\chuan\OneDrive\Desktop\10.17_connect_mongoD_練習\test.py", line 56, in <module>
    x_new = json.dumps(x)
  File "C:\Users\chuan\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "C:\Users\chuan\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Users\chuan\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "C:\Users\chuan\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type InsertManyResult is not JSON serializable

I want function can output in Json like this

{“ok” : 1, “msg” : [{ “name” : “Moma”, “Age” : 33} , { “name” :
“Kara”, “Age” : 44} ], “count”: 2 }

Hi @j_ton and welcome to the MongoDB community forum!!

The insert_one and insert_many functions return instance of InsertOneResult and
InsertManyResults respectively.
Hence the objects are not JSON serialisable.

However since currently the InsertOneResult object do not contain the full documents but rather only the inserted _id, there may not be a method to show exactly the information in your desired example.

The following code below is an example to do the following:

json_object = json.dumps(dict(mycol.find_one({"_id": x.inserted_id}, { "_id": 0, “name” : 1, “Age” : 1 }))) 
print(json_object)

{ “name” : “Moma”, “Age” : 33} 

Let us know if you have further queries.

Best Regards
Aasawari

3 Likes

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