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.

5
  • you want to sort appointments based on which fields ? Commented Oct 31, 2017 at 20:15
  • Not based on fields. Based on which item was added in the database the most recently Commented Oct 31, 2017 at 20:17
  • @Dilli You could use capped collections 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 Commented Oct 31, 2017 at 20:26
  • are you using ObjectID as key in your collection? Commented Oct 31, 2017 at 20:31
  • If you just need to reverse the result this might be redundant, you could just loop backwards Commented Oct 31, 2017 at 20:35

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.