如何检查 MongoDB 数据库中是否已存在某些内容?

How can I check if something already exists in a MongoDB database?

我已经尝试学习 MongoDB [更具体地说是 pymongo],我正在尝试将它与 discord.py 结合使用来为机器人创建库存系统。机器人获取一个用户 ID,然后应该在数据库中进行比较,这样它就可以附加他们的“库存”(如果它们已经在其中),而不是创建一个全新的。

但是,到目前为止我尝试过的每个解决方案似乎总是失败 - 无论用户 ID 是否在数据库中,它只会在数据库中创建一个具有相同用户 ID 的新条目。

到目前为止我尝试过的解决方案:

userID = ctx.message.author.id
if mycol.collection.count_documents({ 'userID': userID }, limit = 1):
    await ctx.send("**Adding new inventory to the database**")
    mydict = { "userID": userID, "coin": "0", "inv": {"inv1": "", "inv2": "", "inv3": "", "inv4": "", "inv5": ""} }
    y = mycol.insert_one(mydict)
else:
    await ctx.send("**Error: You're already in the database**")

userID = ctx.message.author.id
result = mydb.find({"userID": userID}) 
    if result.count() > 0:  
        await ctx.send("**Error: You're already in the database**")
    else:
        await ctx.send("**Adding new inventory to the database**")
        mydict = { "userID": userID, "coin": "0", "inv": {"inv1": "", "inv2": "", "inv3": "", "inv4": "", "inv5": ""} }
        y = mycol.insert_one(mydict)

userID = ctx.message.author.id
search = mycol.find({'userID': userID})
    if search == True:
            await ctx.send("**Error: You're already in the database**")
        else:
            await ctx.send("**Adding new inventory to the database**")
                    mydict = { "userID": userID, "coin": "0", "inv": {"inv1": "", "inv2": "", "inv3": "", "inv4": "", "inv5": ""} }
            y = mycol.insert_one(mydict)

我做错了什么吗?这些解决方案是否过时了?感谢任何帮助。

[原解决方案:

import pymongo

conn = pymongo.MongoClient("mongodb://localhost:27017/")
userID = 21312313
if conn.mydb.mycol.count_documents({ 'userID': userID }):
    print("**Error: You're already in the database**")
else:
    print("**Adding new inventory to the database**")
    mydict = { "userID": userID, "coin": "0", "inv": {"inv1": "", "inv2": "", "inv3": "", "inv4": "", "inv5": ""} }
    y = conn.mydb.mycol.insert_one(mydict)

运行 正常 python 这有效。

这是因为您将 MongoDB 连接定义为 conn,数据库称为 mydb,集合称为 mycol

MongoDB 的结构如下:连接 -> 数据库 -> 集合 -> 文档 -> Key/Value

您的解决方案是:

import pymongo

conn = pymongo.MongoClient("mongodb://localhost:27017/")
userID = ctx.message.author.id
if conn.mydb.mycol.count_documents({ 'userID': userID }):
    await ctx.send("**Error: You're already in the database**")
else:
    await ctx.send("**Adding new inventory to the database**")
    mydict = { "userID": userID, "coin": "0", "inv": {"inv1": "", "inv2": "", "inv3": "", "inv4": "", "inv5": ""} }
    y = conn.mydb.mycol.insert_one(mydict)