user3425344
user3425344

Reputation: 3537

Sending a json object in save method of mongopy

I want to update a record in mongodb using save method.

I am using save method instead of update method because i want to remove the previous doc and replace it with a new one(but with same ObjectId).

I am getting the new object as a post request object.I also receive a emailid with which i will identify the record i want to update.

This code works:

db.doctors.save({"_id":ObjectId(doc_id),"name":"sharath","email":"[email protected]"})

but i want something like this:

db.doctors.save({"_id":ObjectId(doc_id),request.get_json()})

But this isn't working.Is there any way i can send the json object into save method instead of specifying each field?

I am using mongodb database,pymongo in flask


This is how i got it working with the help of yogesh's answer:

newDoc  = request.get_json()
newDoc["_id"]=ObjectId(doc_id)
db.doctors.save(newDoc)

Upvotes: 1

Views: 73

Answers (1)

Neo-coder
Neo-coder

Reputation: 7840

I am doing this on mongo shell, this will help to convert into in pymongo .

Let's consider your request.get_json() data looks like this :

var jsonObj = {"name":"sharath","email":"[email protected]"}

so above jsonObj append _id as below :

jsonObj._id = ObjectId(doc_id)

and used this jsonObj in save like this :

db.doctors.save(jsonObj)

Hope this will help you :)

Upvotes: 1

Related Questions