I want to return Json result like below,
contains is it successfully 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 }
CodePudding user response:
the .modified_count
and for modified_data in mycol.find().sort("_id", -1).limit(#num):
are the key
see below, I'm pretty close, here is what I solve
import pymongo
import datetime
import json
def init_db(ip, db, coll):
myclient = pymongo.MongoClient('mongodb://' ip '/')
mydb = myclient[db]
mycol = mydb[coll]
return mydb, mycol
def change_db_data(myquery_json, one_or_many_bool, newvalues_json ):
if one_or_many_bool == True:
x = mycol.update_many(myquery_json, newvalues_json)
else:
x = mycol.update_one(myquery_json, newvalues_json)
return x
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)
myquery_str = input("Enter ur query: ")
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))
myquery_json =json.loads(myquery_str)
newvalues_json =json.loads(newvalues_str)
x = change_db_data(myquery_json, one_or_many_bool, newvalues_json)
print(x)
print(x.modified_count, "documents updated.")
number_of_update_data = int(x.modified_count)
for modified_data in mycol.find().sort("_id", -1).limit(number_of_update_data):
print(modified_data)
# 1 means success
return_status_str = { "ok" : 1 , "msg" : modified_data , "count" : number_of_update_data}
print(return_status_str)
and the ur expect output (I haven't nicely print 3 modified data in msg
, but there is close)
{'ok': 1, 'msg': {'_id': ObjectId('6348d73be94317989175dc31'), 'name': 'Kim', 'ID': 0, 'Age': 44, 'time': datetime.datetime(2022, 10, 17, 9, 11, 24), 'Update_ID': '99999'}, 'count': 3}