1

I want to extract last objectID of a document from a collection in python and want to store it in python object.

I am doing something like this

db.dataset2.find().sort( {'_id': -1 } ).limit(1);

But it gives me an error.

TypeError: if no direction is specified, key_or_list must be an instance of the list

Please help.

2 Answers 2

5

You are doing it wrong. The .sort takes a key or list and optional direction as arguments.

db.dataset2.find().sort('_id', pymongo.DESCENDING).limit(1)[0]['_id'];

or

db.dataset2.find().sort('_id', -1).limit(1)[0]['_id'];
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, your second line of code worked fine for me.
1
cursor = mycol.find().sort('_id', -1).limit(1)
for document in cursor:
    print(document)

1 Comment

While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.