【问题标题】:Is there a way to check if a collection.find returns false using PyMongo?有没有办法使用 PyMongo 检查 collection.find 是否返回 false?
【发布时间】:2020-09-18 10:20:59
【问题描述】:

我正在使用 PyMongo 用 discord.py 制作一个基本的货币机器人,但是,用户可以多次注册到数据库中。

async def register(ctx):
    insert = {"userid":ctx.message.author.id,"cash":0}
    collection.insert_one(insert)
    await ctx.send('okie dokie you are registered')

这是 register 命令的代码,但我不确定如何检查 collection.find 查询是否返回 true 或 false。有谁知道如何使用它作为支票,或任何方式来检查他们是否已经注册?

【问题讨论】:

    标签: python pymongo discord.py


    【解决方案1】:

    你可以使用find_one(),它要么返回obj,要么返回None。

    async def register(ctx):
        existing = collection.find_one({"userid": ctx.author.id})
        if not existing:
            # register the user
        else:
            await ctx.send("Sorry, you're already registered.")
    

    参考资料:

    • collection.find_one() - 它声明“返回单个文档,如果没有找到匹配的文档,则返回 None。”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-04
      • 2022-10-04
      • 2020-11-25
      • 2014-12-22
      • 1970-01-01
      • 2010-10-26
      • 1970-01-01
      相关资源
      最近更新 更多