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
Use MongoDB Aggregate and select only top record (descending)
To select only the top record in descending order using MongoDB aggregate, use the $sort stage to order documents and the $limit stage to restrict the result to one document.
Syntax
db.collection.aggregate([
{ $sort: { fieldName: -1 } },
{ $limit: 1 }
]);
Sample Data
db.demo267.insertMany([
{ id: 100, "Name": "Chris" },
{ id: 100, "Name": "Adam" },
{ id: 100, "Name": "David" },
{ id: 100, "Name": "Bob" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e4811951627c0c63e7dbaab"),
ObjectId("5e48119e1627c0c63e7dbaac"),
ObjectId("5e4811a51627c0c63e7dbaad"),
ObjectId("5e4811ab1627c0c63e7dbaae")
]
}
View All Documents
db.demo267.find();
{
"_id": ObjectId("5e4811951627c0c63e7dbaab"),
"id": 100,
"Name": "Chris"
}
{
"_id": ObjectId("5e48119e1627c0c63e7dbaac"),
"id": 100,
"Name": "Adam"
}
{
"_id": ObjectId("5e4811a51627c0c63e7dbaad"),
"id": 100,
"Name": "David"
}
{
"_id": ObjectId("5e4811ab1627c0c63e7dbaae"),
"id": 100,
"Name": "Bob"
}
Method 1: Using Aggregate Pipeline
db.demo267.aggregate([
{ $sort: { Name: -1 } },
{ $limit: 1 }
]);
{
"_id": ObjectId("5e4811a51627c0c63e7dbaad"),
"id": 100,
"Name": "David"
}
Method 2: Using find() with sort() and limit()
db.demo267.find().sort({ Name: -1 }).limit(1);
{
"_id": ObjectId("5e4811a51627c0c63e7dbaad"),
"id": 100,
"Name": "David"
}
Key Points
- Use
-1for descending order and1for ascending order in$sort. - The aggregate pipeline approach provides more flexibility for complex operations.
- Both methods return "David" as it comes last alphabetically.
Conclusion
Use $sort with -1 followed by $limit: 1 in an aggregation pipeline to select the top record in descending order. The find().sort().limit() method provides a simpler alternative for basic sorting needs.
Advertisements
