Trying to retrieve guild prefix with MongoDB

I’m trying to setup MongoDB with my bot. I get it to connect, but I cannot retrieve guild prefixes when I define command_prefix.

My current code is:

import discord
from discord.ext import commands
import pymongo
from pymongo import MongoClient

cluster = MongoClient("url im not showing")
db = cluster["Cluster0"]
collection = db["Guild Prefixes"]

def get_prefix(bot, message):
    for x in collection.find({"Guild ID":}):
        prefix = x["Prefix"]
    return prefix

client = commands.Bot(command_prefix=get_prefix, intents=discord.Intents.all(), case_insensitive=True)

I’m getting the following error:

File "", line 11, in get_prefix
    return prefix
UnboundLocalError: local variable 'prefix' referenced before assignment

My current table looks like:

enter image description here

How can I fix this error?


It looks like the id returned from is of type int which can be seen in the documentation, but it’s stored as a string in MongoDB.

You could convert the ID to a string in the filter like so: collection.find({"Guild ID": str(})

Or you can update the documents to store the ID as an int so a conversion isn’t necessary.