Can I just get the first item in a Cursor object (pymongo)?
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.
.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!")