user3787092 user3787092 - 2 months ago 8
Python Question

pymongo+MongoDB: How to find _id in pymongo?

I want to find the

_id
of a document of a collection
(mycol)
where
"name":"John"
. I have inserted the document but want to find the
_id
of document. Is it possible ? I am trying as

result = db.mycol.find({"_id": {"name": "John"}})


But it is returning a cursor object.


pymongo.cursor.Cursor object at 0x00000000030E3DD8>


Then I tried as

for itm in result:
print (itm)


But it is not printing anything.

Answer

Try it like that

result = db.mycol.find({"name": "John"})
for item in result:
    print(item['_id'])

Just have a look at the docs to see how to use pymongo

Comments