【发布时间】:2022-01-07 15:18:33
【问题描述】:
我慢慢地对此感到绝望。我正在尝试从先前定义的数据库中获取一个非常具体的条目。为此,我定义了我的数据库:
test = cluster["folder1"]["example"]
这里有keys 和value,看起来像这样:
现在我想使用find_one() 或find() 方法来查找此条目。数据库中有更多条目。
我已经设法用loop 浏览了该集合,并且该条目也显示了:
def get_key(guild, answer):
for x in test.find({}, {f"{answer}"}): # The searched "answer" is defined before by a command, not needed for this matter
print(x)
编辑:也许我需要提一下:“答案”也可以有不同的值,例如“量子”,然后可能“分配”给“这是量子”或“finger”,它被“分配”给“This is a finger”。因此,我不能使用test.find_one({"test: "FAILUR"}),需要想办法找到value 的key“答案”
看起来像这样:
{'_id': ObjectId('Removed')}
{'_id': ObjectId('Removed')}
{'_id': ObjectId('Removed'), 'test': 'FAILUR'} # I just need FAILUR
我现在想显示“FAILUR”而不总是使用for 循环。因此,使用find_one() 方法是否更容易、更快捷?
我已经试过了:
print(test.find_one({f"{answer}": f"{answer}"})) # Outputs None
print(test.find({}, {f"{answer}"})) # prints <pymongo.cursor.Cursor object at 0x7fc6d482XXX>
此外,我查看了以下帖子,但没有得到任何地方:
https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/ https://docs.mongodb.com/manual/reference/method/db.collection.findOne/
How to select a single field for all documents in a MongoDB collection?
How to read a specific key-value pair from mongodb collection
还有更多。提前致谢!
【问题讨论】:
-
test.find_one({f"{answer}": f"{answer}"}- 我认为你在正确的轨道上,但关键和价值在这里是一样的。所以如果answer是"test",它将等价于find_one(["test": "test"}) -
@SergioTulentsev 是的,我想这只是我试图测试什么是可能的。不知何故,我找不到只需要
answer然后得到value的方法... -
查找运算符
$exists -
@SergioTulentsev 谢谢。这使我更接近我正在寻找的东西。现在我只需要找到一种方法来从中提取
value。print(test.find_one({f"{answer}": {"$exists": True}}))现在返回我的for-loop 之前所做的。 -
虽然不太一样。这不包括没有答案的文件。
标签: python mongodb discord.py