Getting an object from a set of object identifiers

I am trying to loop through objectid from mongodb.

print agent_ids

      

gives a set of identifiers:

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

      

Next cycle:

for agent_id in agent_ids:
    print agent_id

      

gives:

...
542de00c763f4a7f558be133
542de00c763f4a7f558be130
542de00c763f4a7f558be131

      

How to get agent_id

out of the loop including ObjectId()

?

+3


source to share


1 answer


Use the function repr()

:

for agent_id in agent_ids:
    print repr(agent_id)

      

Will return

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

      



The reason this works is because, by default, when you print each item in the list, the instance will be converted to its string representation before printing it out - when you call the function repr

, the custom representation is printed:

In documents:

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

When printing the list in the original example, it used a view repr

for every item in the list, and so we need to emulate this behavior.

0


source







All Articles