How do I sort records in mongodb?

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

Share:   fb twitter linkedin
Answers
Brian
Brian
Moderator
622 Points
86 Posts
         

Try following:

db.getCollection('my-collection').find().sort({"created" : -1})
Posted On: 24-Sep-2021 06:55
Rahul Maurya
Rahul M...
Teacher
1330 Points
230 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
Member
178 Points
44 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