Python get last row in MongoDB database (without looping)

444 views Asked by At

Based on this post: Get the latest record from mongodb collection

I got the following to work:

docs = dbCollectionQuotes.find({}).limit(1).sort([('$natural',  pymongo.DESCENDING)])
for doc in docs:
    pprint.pprint(doc)

But since we know there is only going to be one row coming back, is there any way to get that one row without looping through the cursor that is returned? I don't think we can use find_one() because of the limit and the sort.

1

There are 1 answers

0
elomage On BEST ANSWER

Use next(). This works for me:

doc = dbCollectionQuotes.find().limit(1).sort([('$natural', -1)]).next()