Neil
Neil

Reputation: 8247

How to extract last objectID of mongoDB document in Python?

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.

Upvotes: 1

Views: 1724

Answers (2)

Andrei S. Klimanov
Andrei S. Klimanov

Reputation: 5

cursor = mycol.find().sort('_id', -1).limit(1)
for document in cursor:
    print(document)

Upvotes: 1

Sede
Sede

Reputation: 61225

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'];

Upvotes: 5

Related Questions