0

How can I sort a list of objects in python mongo.

I am creating a view that shows all the members; I don't have timestamp nothing like that in my models.

How would I sort this based on database list; like descend results or ascend the results?

in my case I have appointments; I want to show descend the appointments(So like the latest appointments in the db is sorted first then older appointments later on the arr or mongo object).

get_appointments = appointment.objects.all()

So I want to be able to descend appointment.

Biplov
  • 1,136
  • 1
  • 20
  • 44
  • you want to sort appointments based on which fields ? – YouneL Oct 31 '17 at 20:15
  • Not based on fields. Based on which item was added in the database the most recently – Biplov Oct 31 '17 at 20:17
  • @Dilli You could use capped collections https://www.mongodb.com/blog/post/capped-collections. If you don't have a timestamp and the insertion order is random there is no way that you can sort the entries like you suggest, how should the database know about it? Maybe you need to clearify that point – Matthias Herrmann Oct 31 '17 at 20:26
  • are you using ObjectID as key in your collection? – YouneL Oct 31 '17 at 20:31
  • If you just need to reverse the result this might be redundant, you could just loop backwards – Matthias Herrmann Oct 31 '17 at 20:35

1 Answers1

0

You can sort your list using _id fields, every ObjectId field represent timestamp, here is an example using mongo shell:

db.appointment.find().sort( { _id: -1 } );

it will show you all appointment in descending order

YouneL
  • 8,152
  • 2
  • 28
  • 50