PyMongo 的问题:检查集合
Problems with PyMongo: Checking a collection
我目前正在使用 Python 学习 MongoDB,并且我正在使用 discord 机器人尝试我的项目。我想做一些事情,但我不知道怎么做。
第一个问题如下:
@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)
机器人发送此消息:
{'_id': '<id>', 'name': '<name>', 'permission': 'x'}
但我希望它像这样发送:
<name> has permission x
第二个问题如下:
我想检查用户是否有权限 "x" 并打印如下内容:
<name> has permission admin
我该如何解决并做到这一点?
在此细分中:
for y in cursor:
await bot.say(y)
y
实际上是一个 Python dict
正如你在打印出来时看到的那样。在这种情况下,您所要做的就是从字典中获取所需的值并自己创建字符串。
那将是(使用 str 的 format() 方法:
answer = "{} has permission {}".format(y["name"], y["permission"])
因此,您需要做的就是 return 而不是像 y 这样的:
for y in cursor:
answer = "{} has permission {}".format(y["name"], y["permission"])
await bot.say(answer)
我目前正在使用 Python 学习 MongoDB,并且我正在使用 discord 机器人尝试我的项目。我想做一些事情,但我不知道怎么做。
第一个问题如下:
@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)
机器人发送此消息:
{'_id': '<id>', 'name': '<name>', 'permission': 'x'}
但我希望它像这样发送:
<name> has permission x
第二个问题如下:
我想检查用户是否有权限 "x" 并打印如下内容:
<name> has permission admin
我该如何解决并做到这一点?
在此细分中:
for y in cursor:
await bot.say(y)
y
实际上是一个 Python dict
正如你在打印出来时看到的那样。在这种情况下,您所要做的就是从字典中获取所需的值并自己创建字符串。
那将是(使用 str 的 format() 方法:
answer = "{} has permission {}".format(y["name"], y["permission"])
因此,您需要做的就是 return 而不是像 y 这样的:
for y in cursor:
answer = "{} has permission {}".format(y["name"], y["permission"])
await bot.say(answer)