How to order by timestamp (descending order) from objectId on a queryset in mongoengine?

Viewed 571

I have a collection, say Cages. Cages has the following fields: _id (generated on saving to db), cage_type (string type field)

I'm performing a query. I want to order by timestamp that the objectid contains in descending order.

Usually we can access the timestamp by: YourObject.id.generation_time

But i can't seem to figure it out in a order_by query. There's no mention in the docs either.

I have tried:

query = Cage.objects.order_by('-_id.generation_time').first()
query = Cage.objects.order_by('-id.generation_time').first()
query = Cage.objects.order_by('-_id.getTimestamp()').first()

But none have worked out.

Would really appreciate any help. Thank you for your time!

1 Answers

You can sort by the ObjectId directly, since it encapsulates a creation timestamp, it will get ordered naturally by creation datetime.

query = Cage.objects.order_by('-id').first()
Related