How do I sort records in mongodb?

beginer
beginer
Member
1328 Points
43 Posts

How do I sort records in mongodb? I'm using following shell command in Robo 3t:

db.getCollection('my-collection').sort({"created" : -1})

But getting error as:

Am I doing something wrong?

Views: 591
Total Answered: 3
Total Marked As Answer: 2
Posted On: 24-Sep-2021 01:57

Share:   fb twitter linkedin
Answers
Brian
Brian
Moderator
2232 Points
14 Posts
         

Try following:

db.getCollection('my-collection').find().sort({"created" : -1})
Posted On: 24-Sep-2021 06:55
Rahul Maurya
Rahul M...
Teacher
4822 Points
23 Posts
         

The basic syntax of sort() method is as follows:

db.COLLECTION_NAME.find().sort({KEY:1});

So, you can use following:

db.getCollection('my-collection').find({}).sort({"created" : -1})
Posted On: 25-Sep-2021 22:46
Priya
Priya
Participant
936 Points
28 Posts
         

Use following for Ascending order:

db.getCollection('my-collection').find({}).sort({"created" : 1})

For descending order:

db.getCollection('my-collection').find({}).sort({"created" : -1})
Posted On: 25-Sep-2021 22:48
Thanks.
 - beginer  27-Sep-2021 21:11
 Log In to Chat