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):
        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):
        if one_or_many_bool == True:
            x = mycol.insert_many(insert_values_json)
            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)

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)
x_new = json.dumps(x)
  • the tried code output:
Traceback (most recent call last):
  File "C:\Users\chuan\OneDrive\Desktop\10.17_connect_mongoD_練習\", line 56, in <module>
    x_new = json.dumps(x)
  File "C:\Users\chuan\AppData\Local\Programs\Python\Python310\lib\json\", line 231, in dumps
    return _default_encoder.encode(obj)
  File "C:\Users\chuan\AppData\Local\Programs\Python\Python310\lib\json\", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Users\chuan\AppData\Local\Programs\Python\Python310\lib\json\", line 257, in iterencode
    return _iterencode(o, 0)
  File "C:\Users\chuan\AppData\Local\Programs\Python\Python310\lib\json\", 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 }))) 

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

Let us know if you have further queries.

Best Regards


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