The Python Oracle

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

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

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Over a Mysterious Island

--

Chapters
00:00 Question
01:56 Accepted answer (Score 29)
02:29 Answer 2 (Score 2)
02:54 Thank you

--

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

Accepted answer links:
[.find_one()]: http://api.mongodb.org/python/current/ap...
[PyMongo Cursor]: http://api.mongodb.org/python/current/ap...

--

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.