0
0
MongoDBquery~5 mins

sort method ascending and descending in MongoDB

Choose your learning style9 modes available
Introduction
Sorting helps you organize data so you can find what you need faster. You can put data in order from smallest to largest or largest to smallest.
When you want to see a list of products from cheapest to most expensive.
When you need to show recent messages first in a chat app.
When you want to arrange students by their scores from highest to lowest.
When you want to display events starting from the earliest date.
When you want to find the top-rated movies by sorting ratings in descending order.
Syntax
MongoDB
db.collection.find().sort({ field: 1 })  // ascending order

db.collection.find().sort({ field: -1 }) // descending order
Use 1 for ascending order (smallest to largest).
Use -1 for descending order (largest to smallest).
Examples
Sort products by price from lowest to highest.
MongoDB
db.products.find().sort({ price: 1 })
Sort messages by date from newest to oldest.
MongoDB
db.messages.find().sort({ date: -1 })
Sort students by score from highest to lowest.
MongoDB
db.students.find().sort({ score: -1 })
Sample Program
This example inserts three products with different prices. Then it finds all products sorted by price from lowest to highest.
MongoDB
use shop

// Insert sample data
 db.products.insertMany([
   { name: "Pen", price: 1.5 },
   { name: "Notebook", price: 3.0 },
   { name: "Eraser", price: 0.5 }
 ])

// Find products sorted by price ascending
 db.products.find().sort({ price: 1 }).toArray()
OutputSuccess
Important Notes
Sorting works on any field that exists in your documents.
If two documents have the same value in the sorted field, their order is undefined.
You can sort by multiple fields by adding more fields in the sort object, like { age: 1, name: -1 }.
Summary
Use sort({ field: 1 }) to order data from smallest to largest.
Use sort({ field: -1 }) to order data from largest to smallest.
Sorting helps you organize and find data quickly.