![](/img/trans.png)
[英]How can I update a whole collection in MongoDB and not document by document?
[英]How can I update a MongoDB document with python?
我想做的是用python和discord.py更新MongoDB文档,但是我输入的代码不起作用。
elif string2 == "add":
if string3 == "administrator":
cur = coll.find({"_id" : string1.id})
for doc in cur:
if doc["perm"] == "administrator":
await self.bot.say("Permission {} already found on db for user {}".format(string3, string1.name))
else:
db.users.update_one({"_id" : string1.id, "name" : string1.name, "perm" : "administrator"}, upsert=False)
await self.bot.say("Permissions updated on db for user {}".format(string1.name))
以下是错误。
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: update_one() missing 1 required positional argument: 'update'
来自用户集合的文档:
_id: "191598787410526208"
name: "Stevyb0t"
perm: "administrator"
基本上是其他人评论的内容,但有一些格式使其更清晰易懂:
db.users.update_one(
{"_id": string1.id},
{"$set":
{"name": string1.name,
"perm": "administrator"
}})
我还删除了upsert=False
因为无论如何这都是默认值,因此您无需指定它-尽管明确是很有用的
编辑 :阅读所有评论,建议已经做出,以使接受的评论成为答案,所以就在这里。 我的回答和那句话没什么不同
如果您的id是字符串,则可能需要将其转换为ObjectId。 另外,您可以打印更新结果,并检查是否成功:
from bson import ObjectId
result = db.users.update_one(
{"_id": ObjectId(string1.id)},
{"$set":
{"name": string1.name,
"perm": "administrator"}
})
logger.debug('update result: {}'.format(result.raw_result))
if result.matched_count > 0:
# Success code goes here
pass
else:
# Failure code goes here
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.