如何用 python 更新 MongoDB 文档?
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
我想做的是用 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