简体   繁体   English

PyMongo问题:检查集合

[英]Problems with PyMongo: Checking a collection

I'm currently learning MongoDB using Python and I'm trying my projects with a discord bot. 我目前正在使用Python学习MongoDB,并且正在使用Discord机器人尝试项目。 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: 我想检查用户是否具有权限“ x”并打印如下内容:

<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. y实际上是Python dict如打印时所见。 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: 那将是(使用strformat()方法:

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

So, all you need to do is return that instead of y like tis: 因此,您所需要做的就是返回它,而不是像tis一样返回y:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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