从一组对象 ID 中获取对象 ID

getting objectid from set of object ids

我正在尝试循环遍历来自 mongodb 的一组 objectid。

print agent_ids

生成一组 ID:

...ObjectId('542de00c763f4a7f558be133'), ObjectId('542de00c763f4a7f558be130'), ObjectId('542de00c763f4a7f558be131')])

以下循环:

for agent_id in agent_ids:
    print agent_id

产量:

...
542de00c763f4a7f558be133
542de00c763f4a7f558be130
542de00c763f4a7f558be131

如何从循环中获取 agent_id 以包含 ObjectId()

使用repr()函数:

for agent_id in agent_ids:
    print repr(agent_id)

会return

ObjectId('542de00c763f4a7f558be133')
ObjectId('542de00c763f4a7f558be130')
ObjectId('542de00c763f4a7f558be131')

之所以可行,是因为默认情况下,当打印列表中的每个元素时,实例将在打印之前转换为其字符串表示形式 - 当您调用 repr 函数时,自定义表示形式打印:

根据文档:

A class can control what this function returns for its instances by defining a repr() method.

在原始示例中打印列表时,它使用 repr 表示列表中的每个元素,因此我们需要模仿该行为。