The Python Oracle

Can I just get the first item in a Cursor object (pymongo)?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Drifting Through My Dreams

--

Chapters
00:00 Can I Just Get The First Item In A Cursor Object (Pymongo)?
01:28 Accepted Answer Score 30
01:54 Answer 2 Score 2
02:11 Thank you

--

Full question
https://stackoverflow.com/questions/3464...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #mongodb #pymongo

#avk47



ACCEPTED ANSWER

Score 30


.find_one() would return you a single document matching the criteria:

cdb[collection].find_one(query_commands_here)

Note that the PyMongo Cursor does not have a hasNext() method. What I would do is to call cursor.next() and handle the StopIteration exception:

try:
    record = cursor.next()
except StopIteration:
    print("Empty cursor!")



ANSWER 2

Score 2


You can also do the following (without having to handle the StopIteration exception):

cur = cdb[collection].find(query_commands_here)
record = next(cur, None)
if record:
    # Do your thing

This works because python's built in next() will return the default value when it hits the end of the iterator.