检查pymongo中是否存在文档

时间:2020-06-22 09:50:03

标签: python mongodb discord pymongo

我正在尝试查看数据库中是否已存在文档 这是我的初始代码:

myclient = pymongo.MongoClient("server link")
mydb = myclient["snkr"]
dblist = myclient.list_database_names()
collist = mydb.list_collection_names()
mycol = mydb["auth_servers"]

因此它需要一个名为snkr的数据库和一个名为auth_servers的集合,现在要检查文档是否已经存在,我使用代码:

server_name = ctx.guild
    server_id = ctx.guild.id
    if mycol.count_documents({ 'ServerName':str(server_name), 'ServerID': str(server_id) }, limit = 1):
        await ctx.send(f"This server is already authorized")
    else:
        #code that inserts the value into the DB in case there isn't already one

我尝试了不同的方法:

if mydb.mycol.count_documents({ 'ServerName':str(server_name), 'ServerID': str(server_id) }, limit = 1):

if mydb.count_documents({ 'ServerName':str(server_name), 'ServerID': str(server_id) }, limit = 1):

if mydb.auth_servers.count_documents({ 'ServerName':str(server_name), 'ServerID': str(server_id) }, limit = 1):

if mydb["auth_servers"].count_documents({ 'ServerName':str(server_name), 'ServerID': str(server_id) }, limit = 1):

但是它们都不起作用

1 个答案:

答案 0 :(得分:0)

已解决:

$1