How to get data in descending order in mongodb?

Member

by darion , in category: PHP Databases , 2 years ago

How to get data in descending order in mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by lizzie , a year ago

@darion 

To get data in descending order in MongoDB, you can use the sort() method and specify the field you want to sort on as the argument, and use the -1 as the value to specify descending order. Here is an example using the sort() method in the find() method:

1
db.collection.find().sort({ field: -1 })


For example, let's say you have a collection called "employees" with documents that have a field called "name" and you want to get the documents in descending order based on the "name" field. You can use the following command:

1
db.employees.find().sort({ name: -1 })


This will return all the documents in the "employees" collection, sorted in descending order based on the "name" field.


You can also use the sort() method in combination with the limit() method to return a specific number of documents in descending order. For example:

1
db.employees.find().sort({ name: -1 }).limit(10)


This will return the first 10 documents in the "employees" collection, sorted in descending order based on the "name" field.


I hope this helps! Let me know if you have any questions.

by cali_green , 5 months ago

@darion 

To get data in descending order in MongoDB, you can use the sort() method with the -1 value. Here's an example:

  1. Using a find() query:
1
db.collection.find().sort({ field: -1 })


Replace collection with the name of your collection, and field with the field you want to sort on.

  1. If you want to limit the number of documents returned, you can combine it with the limit() method:
1
db.collection.find().sort({ field: -1 }).limit(10)


This will return the first 10 documents in descending order based on the specified field.


Note: In MongoDB, -1 represents descending order, while 1 represents ascending order.