Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

so I created a Cursor object by having

cdb=self.mongo['bleh_bleh_bleh_setup_here']
data=cdb[collection].find(query_commands_here)

Don't worry about the syntax above. Just assume that I can successfully create such cursor object

I know I can do a for loop to iterate through the object, but all I want is the very first item of this object. Is there a more efficient way than looping through?

EDIT:

to make things more clear, the 'bleh_bleh_bleh_setup_here' is simply path to connect to the desired mongoDB, and 'query_commands_here' are queries like {field1:{'$gt':num1}, field2:{'$ne':num2}} that sort of things. The line

data=cdb[collection].find(query_commands_here)

will give me a Cursor object that I can iterate with a for loop. So things like

for item in data:
    print item

will print out each of the entry in the object. It works nicely. However, according to the documentation, this cursor object should have method called .hasNext(), which should return True if there's a next entry. So far, I haven't found a way to get it to work for some odd reason. data.next() does give me an entry though. I want to make sure I can have that condition to make sure I don't call .next() for a cursor object that contains nothing, though I don't foresee this kind of situation happening, but I would assume it'd occur at some point.

like image 304
JChao Avatar asked Jan 07 '16 00:01

JChao


People also ask

What is Pymongo cursor object?

As we already discussed what is a cursor. It is basically a tool for iterating over MongoDB query result sets. This cursor instance is returned by the find() method.

How can I tell if Pymongo cursor is empty?

Check if the Cursor object is empty or not? Approach 1: The cursor returned is an iterable, thus we can convert it into a list. If the length of the list is zero (i.e. List is empty), this implies the cursor is empty as well.


2 Answers

.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!")
like image 176
alecxe Avatar answered Oct 02 '22 12:10

alecxe


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.

like image 21
rouble Avatar answered Oct 02 '22 14:10

rouble