Mongodb and Discord.py collection.update_one(update) NameError: name 'update' is not defined when trying to update mongodb collection

Viewed 367

I have been trying to create a simple discord bot using discord.py, I have also begun to use mongodb to store data and keep my bot online while my laptop is powered off. My goal with the code posted below is so when anyone types the word 'python' it returns the word 'accepted'. However when I run this code it shows the error:

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

The code shown at the bottom of this question is my attempt to get this working, I have previously asked people for help on this which is where the DuplicateKeyError part came from. Before that was added the database would not update and showed a duplicate key error whenever the word python is said in the guild. This error message still shows however it is now handled as an exception: (error message shown below, I replaced the actual user ID with USER_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 }'}

The main error is coming from the line collection.update_one as it is saying update is not defined.

@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!')

Any help on this would be really appreciated. Thanks in advance

2 Answers

update is not defined.

It would be

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

With the first pair of curly braces finding the document then the second is setting the new value which you could use find_one for and just add a value to the score.

Easy Way:

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