简体   繁体   中英

Problems with PyMongo: Checking a collection

I'm currently learning MongoDB using Python and I'm trying my projects with a discord bot. I would like to do some things but I don't know how to do them.

The first problem is the following:

@bot.command(pass_context=True)
async def test(ctx, arg:str=None):
    db = client.db_test
    collection = db["test"]
    cursor = collection.find({"permission" : arg})
    if perm is not None:
        if perm == "x":
            for y in cursor:
                await bot.say(y)

The bot sends this message:

{'_id': '<id>', 'name': '<name>', 'permission': 'x'}

But I want it to send like:

<name> has permission x

The second question is the following:

I want to check if a user has permission "x" and print something like:

<name> has permission admin

How can I resolve and do that?

In this segment:

            for y in cursor:
                await bot.say(y)

y is actually a Python dict as you can see when printing it out. In this case, all you have to do is take the values you want from the dictionary and create your string yourself.
That would be (using str 's format() method:

answer = "{} has permission {}".format(y["name"], y["permission"])

So, all you need to do is return that instead of y like tis:

            for y in cursor:
                answer = "{} has permission {}".format(y["name"], y["permission"])
                await bot.say(answer)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM