How to sort mongodb with pymongo How to sort mongodb with pymongo python python

How to sort mongodb with pymongo


.sort(), in pymongo, takes key and direction as parameters.

So if you want to sort by, let's say, id then you should .sort("_id", 1)

For multiple fields:

.sort([("field1", pymongo.ASCENDING), ("field2", pymongo.DESCENDING)])


You can try this:

db.Account.find().sort("UserName")  db.Account.find().sort("UserName",pymongo.ASCENDING)   db.Account.find().sort("UserName",pymongo.DESCENDING)  


This also works:

db.Account.find().sort('UserName', -1)db.Account.find().sort('UserName', 1)

I'm using this in my code, please comment if i'm doing something wrong here, thanks.