【问题标题】:TypeError: update() missing 1 required positional argument: 'document'类型错误:更新()缺少 1 个必需的位置参数:“文档”
【发布时间】:2019-12-18 06:24:39
【问题描述】:

我尝试将比较属性和 $set 属性绑定在一个变量中,并渲染到 mongodb 中的更新函数。但它给了我以下错误

TypeError: update() 缺少 1 个必需的位置参数:'document'

Python 3 MongoDB

from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
db = client.Mydb
collection = db.sampledb
new_contact = "6369723748"
updatestmt = "{\"ID\" : \"12345\"},{\"$set\" :{\"ID\" : \"67891\",\"Account_Number\" : \"1234 5678 9101\"}}"
print(updatestmt)

cursor = collection.update(updatestmt)
cursor1 = collection.find()

for i in cursor1:
    print(i)

预期结果:

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

实际结果:

Traceback(最近一次调用最后一次):

文件“dbupdate.py”,第 12 行,在

cursor = collection.update(updatestmt)

TypeError: update() 缺少 1 个必需的位置参数:'document'

【问题讨论】:

    标签: python-3.x mongodb


    【解决方案1】:

    pymongo 正在使用字典,而不是字符串。 (错误只是告诉你你正在传递一个字符串,而它至少需要两个参数)。

    因此使用:

    query = {"ID" : "12345"}
    new_values = {"$set" : {"ID" : "67891", "Account_Number" : "1234 5678 9101"}}
    
    cursor = collection.update(query, new_values)
    

    或者,为了匹配你的语法:

    updatestmt = ({"ID" : "12345"}, {"$set" : {"ID" : "67891", "Account_Number" : "1234 5678 9101"}})
    cursor = collection.update(*updatestmt)
    

    顺便说一句:update 现在替换为update_one(根据您的需要)或update_many(如果查询可以匹配多条记录)

    【讨论】:

      【解决方案2】:

      update()deprecated,您应该真正使用 update_one()

      cursor = collection.update({'ID' : '12345'}, {'$set' : {'ID' : '67891', 'Account_Number' : '1234 5678 9101'}})
      

      【讨论】:

      • 嗨,Simon,感谢您的回复,但是我想同时更新许多行。
      • 还有update_many() :) 和 mongo 一样。
      猜你喜欢
      • 2021-04-21
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 2018-09-12
      • 2021-08-05
      • 2021-07-06
      • 2021-08-05
      相关资源
      最近更新 更多