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.
Jump into concepts and practice - no test required
db.collection.find().sort({ field: 1 }) // ascending order
db.collection.find().sort({ field: -1 }) // descending orderdb.products.find().sort({ price: 1 })db.messages.find().sort({ date: -1 })db.students.find().sort({ score: -1 })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()
sort({ age: 1 }) method do in MongoDB?sort({ age: 1 }) means ascending order.score in descending order in MongoDB?{ score: -1 } is correct.db.students.find().sort({ score: 1 })?db.products.find().sort({ price: 2 })category and price. How do you sort first by category ascending, then by price descending?{ category: 1, price: -1 } to sort category ascending, then price descending within each category.