Pymongo 获取随机记录和记录的元素

Pymongo get random record and element of the record

我的 MongoDB

中有这样的记录
{
_id: "611ae422a01534cecce5533d"
firstname:"Test1"
lastname: "Test2"
}

这是我的代码

res = firstnameCollection.aggregate([{'$sample': {'size': 1 }}])
print(list(res))

我想从我的数据库中获取一条随机记录。我有很多像我上面提到的记录。 我得到的输出是记录列表。当我删除列表属性时,我得到:

<pymongo.command_cursor.CommandCursor object at 0x0000021078B82EB0>

我只想输出元素的名字:

Test1

将响应转换为列表后,您可以使用索引检索第一个元素。你可以这样做:

docs = list(res)
first_name = docs[0]['firstname'] if docs and 'firstname' in docs[0] else 'placeholder'

该方法利用空列表是 considered false. It also checks that firstname is in the document 的事实确保您不会得到 IndexError,这样您就不会得到 KeyError