NealWalters
NealWalters

Reputation: 18177

Python get last row in MongoDB database (without looping)

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.

Upvotes: 1

Views: 478

Answers (1)

elomage
elomage

Reputation: 4474

Use next(). This works for me:

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

Upvotes: 3

Related Questions