How do I sort records in mongodb?

beginer
beginer
1576 Points
53 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: 733
Total Answered: 3
Total Marked As Answer: 2
Posted On: 24-Sep-2021 01:57

Share:   fb twitter linkedin
Answers
Brian
Brian
2416 Points
14 Posts
         

Try following:

db.getCollection('my-collection').find().sort({"created" : -1})
Posted On: 24-Sep-2021 06:55
Rahul Maurya
Rahul M...
4960 Points
31 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
1278 Points
37 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