简体   繁体   中英

Python: Script in python to update a record in mongoDB

I am trying to update a record in mongoDb. But i am getting an error

flag = raw_input('do you want to update?')
    if (flag == 'Y' or flag == 'y'):
            student_name = raw_input("enter studentname to update:")
            student_grade = raw_input("enter grade to update:")
            student_record = {'name':student_name,'grade':student_grade}
            db.collection.update({'name':name},"$set":student_record},upsert=0)
            flag = 0

Here i dont know how to update. May be i am following the wrong syntax for update.

Could anyone lend a helping hand?

Here i am using upsert because if record not found for update then it will insert a new record.

You are missing { in your update document. {"$set": student_record} . Also you need to convert "student_grade" to float. By default upsert: False so you don't need to specify. Your if statement can by simplify as: if flag.lower() == 'y':

flag = raw_input('do you want to update?')
if flag.lower() == 'y':
    student_name = raw_input("enter studentname to update:")
    student_grade = float(raw_input("enter grade to update:"))
    db.collection.update_one({'name': student_name}, {"$set": {'grade': student_grade}})

Last and not least the update method is deprecated. You should use the new API. update_one

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