简体   繁体   English

Python:Python中的脚本来更新mongoDB中的记录

[英]Python: Script in python to update a record in mongoDB

I am trying to update a record in mongoDb. 我正在尝试更新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. 我在这里使用upsert,因为如果找不到要更新的记录,则它将插入一条新记录。

You are missing { in your update document. 您在更新文档中缺少{ {"$set": student_record} . {"$set": student_record} Also you need to convert "student_grade" to float. 另外,您需要将“ student_grade”转换为浮点数。 By default upsert: False so you don't need to specify. 默认情况下, upsert: False因此您无需指定。 Your if statement can by simplify as: if flag.lower() == 'y': 您的if语句可以简化为: 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. 最后,并非最不重要的一点是,不建议使用update方法。 You should use the new API. 您应该使用新的API。 update_one

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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