How do I sort records in mongodb?

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

Share:   fb twitter linkedin
Answers
Brian
Brian
2376 Points
13 Posts
         

Try following:

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