简体   繁体   中英

Change string to objectId within json in pymongo+flask and insert it into mongodb

I'm using Swagger+pymongo and I wanted something really simple to convert a string into an ObjectId . How can I do this very easily without touching other db schemas.(Minimal effort)?

Code:

jsonResponse = request.json['business']
# convert business_id Datatype to ObjectId
business_id=ObjectId(jsonResponse['business_id'])

#add business_id (ObjectId)to mongodb
data = collection.insert_one(jsonResponse).inserted_id
return data
response = request.json['business']
response_oid = ObjectId(response['business_id'])

mongo_item = response.copy()
mongo_item['business_id'] = response_oid

return collection.insert_one(mongo_item).inserted_id

Should do the job.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM