Question

I have been trying to sort documents in Mongo collection by ObjectId in descending order from Pymongo and use the last added record using this code

record = collection.find({}).sort('_id', -1).limit(1)

However, I am getting 'expected a character buffer object'error. Not sure what is happening here. Also, if anyone can think of a better way to get the last added record from mongo collection using Pymongo, it will be great help.

No correct solution

OTHER TIPS

for item in collection.find().sort("_id", pymongo.DESCENDING).limit(1):
    # do something with your item.

This error indicates to me that your "collection" variable holds a string, not a PyMongo Collection instance. I need to see the code that sets the "collection" variable to know what mistake you're making. But let's start from the top:

import pymongo
client = pymongo.MongoClient()
collection = client.db
cursor = collection.find({}).sort('_id', -1).limit(1)
record = cursor.next()

This will get you a recently-added document, but not always the most recently added. The timestamp portion of an ObjectId is only precise to one second, and since it's generated on the client machine that inserts the document, ObjectId is subject to clock skew.

If and only if the collection is capped, you can reliably get the last document like:

cursor = collection.find({}).sort('$natural', -1).limit(1)
record = cursor.next()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top