【问题标题】:How can I find a specific collection entry with mongodb?如何使用 mongodb 找到特定的集合条目?
【发布时间】:2022-01-07 15:18:33
【问题描述】:

我慢慢地对此感到绝望。我正在尝试从先前定义的数据库中获取一个非常具体的条目。为此,我定义了我的数据库:

test = cluster["folder1"]["example"]

这里有keysvalue,看起来像这样:

Database picture

现在我想使用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"}),需要想办法找到valuekey“答案”

看起来像这样:

{'_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 谢谢。这使我更接近我正在寻找的东西。现在我只需要找到一种方法来从中提取valueprint(test.find_one({f"{answer}": {"$exists": True}})) 现在返回我的 for-loop 之前所做的。
  • 虽然不太一样。这不包括没有答案的文件。

标签: python mongodb discord.py


【解决方案1】:
test.find( { "test": "FAILUR" } )

这只会返回字段test 的值为FAILUR 的文档

【讨论】:

  • 这肯定会找到它,是的,但answer 也可以不同,取决于命令。想象一下:一次我需要搜索“test”,另一次我需要搜索“quantum”,因此我需要基于“test”或“quantum”显示值的东西。
  • 所以你的意思是你想要任何key 具有价值FAILUR 的所有文档?
  • 你能解释一下具体的用例吗?
  • 我只想在该集合中查找我定义的匹配项。例如,我将“人”定义为“答案”,然后我希望我的机器人为key“人”找到value
猜你喜欢
  • 1970-01-01
  • 2012-09-16
  • 1970-01-01
  • 2016-04-28
  • 2019-04-20
  • 1970-01-01
  • 1970-01-01
  • 2014-06-05
  • 2019-08-05
相关资源
最近更新 更多