【发布时间】:2021-08-11 12:24:41
【问题描述】:
我已经尝试学习 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)
我做错了什么吗?这些解决方案是否已经过时?感谢您提供任何和所有帮助。
[原解决方案:https://stackoverflow.com/questions/25163658/mongodb-return-true-if-document-exists]
【问题讨论】:
标签: python mongodb discord.py pymongo