Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 361
Alex Avatar asked Oct 26 '25 14:10

Alex


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()
like image 172
bagerard Avatar answered Oct 28 '25 06:10

bagerard