Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
MongoDB query to 'sort' and display a specific number of values
To sort and display a specific number of values in MongoDB, use the sort() method combined with limit(). The sort() method orders documents while limit() restricts the number of results returned.
Syntax
db.collection.find().sort({field: 1}).limit(number);
Where 1 is for ascending order and -1 is for descending order.
Sample Data
Let us create a collection with documents ?
db.demo254.insertMany([
{"Name": "Chris"},
{"Name": "Adam"},
{"Name": "Bob"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e47a0ab1627c0c63e7dba7f"),
ObjectId("5e47a0b01627c0c63e7dba80"),
ObjectId("5e47a0b71627c0c63e7dba81")
]
}
Display all documents from the collection ?
db.demo254.find();
{ "_id": ObjectId("5e47a0ab1627c0c63e7dba7f"), "Name": "Chris" }
{ "_id": ObjectId("5e47a0b01627c0c63e7dba80"), "Name": "Adam" }
{ "_id": ObjectId("5e47a0b71627c0c63e7dba81"), "Name": "Bob" }
Example 1: Sort in Ascending Order
Sort documents by Name field in ascending order ?
db.demo254.find().sort({"Name": 1});
{ "_id": ObjectId("5e47a0b01627c0c63e7dba80"), "Name": "Adam" }
{ "_id": ObjectId("5e47a0b71627c0c63e7dba81"), "Name": "Bob" }
{ "_id": ObjectId("5e47a0ab1627c0c63e7dba7f"), "Name": "Chris" }
Example 2: Sort and Limit Results
Sort by Name and display only the first 2 records ?
db.demo254.find().sort({"Name": 1}).limit(2);
{ "_id": ObjectId("5e47a0b01627c0c63e7dba80"), "Name": "Adam" }
{ "_id": ObjectId("5e47a0b71627c0c63e7dba81"), "Name": "Bob" }
Key Points
- Use
sort({field: 1})for ascending andsort({field: -1})for descending order. - Chain
limit()aftersort()to restrict the number of results. - Sorting happens before limiting, ensuring you get the top N sorted results.
Conclusion
Combine sort() and limit() methods to efficiently retrieve a specific number of sorted documents. This approach is particularly useful for implementing pagination and getting top results from large collections.
Advertisements
