Mongodb 和 Discord.py collection.update_one(update) 名称错误:尝试更新 mongodb 集合时未定义名称'update'



我一直在尝试使用discord.py创建一个简单的discordbot。我还开始使用mongodb来存储数据,并在笔记本电脑关机时保持我的bot在线。我在下面发布的代码的目标是,当任何人键入单词"python"时,它都会返回单词"accepted"。然而,当我运行此代码时,它显示错误:

collection.update_one(update)    
NameError: name 'update' is not defined

这个问题底部显示的代码是我试图让它发挥作用的,我之前曾向人们寻求帮助,这就是DuplicateKeyError部分的来源。在添加之前,数据库不会更新,并且每当公会中出现单词python时,都会显示重复的密钥错误。这个错误消息仍然显示,但现在它被作为一个异常处理:(下面显示的错误消息,我用user_ID替换了实际的用户ID。(

raise DuplicateKeyError(error.get("errmsg"), 11000, error)
pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection: Bot.Main index: _id_ dup key: { _id: USER_ID }, full error: {'index': 0, 'code': 11000, 'keyPattern': {'_id': 1}, 'keyValue': {'_id': USER_ID}, 'errmsg': 'E11000 duplicate key error collection: Bot.Main index: _id_ dup key: { _id: USER_ID }'}

主要错误来自行集合。update_one,因为它表示未定义更新

@client.event
async def on_message(ctx): 
print(f"{ctx.channel}: {ctx.author}: {ctx.author.name}: {ctx.content}")
if "python" in str(ctx.content.lower()):
post = {"_id": ctx.author.id, "score": 1}
try:
collection.insert_one(post)
except DuplicateKeyError:
collection.update_one(update)
await ctx.channel.send('accepted!')

如有任何帮助,我们将不胜感激。提前感谢

update未定义。

这将是

collection.update_one({"_id": ctx.author.id},
{"$set": {"score": 10}})

第一对大括号查找文档,然后第二对大括号设置新值,您可以使用find_one,只需在分数中添加一个值。

简单方法:

find = {"_id": str(id)}
setdata = {"$set": {"hello": "one"}}
collection.update_one(find, setdata)

最新更新