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
Find oldest/ youngest post in MongoDB collection?
To find oldest/youngest post in MongoDB collection, you can use sort() with limit(1). Use ascending sort (1) for oldest and descending sort (-1) for newest posts based on date fields.
Syntax
// For oldest post
db.collection.find().sort({"dateField": 1}).limit(1);
// For newest post
db.collection.find().sort({"dateField": -1}).limit(1);
Sample Data
db.getOldestAndYoungestPostDemo.insertMany([
{
"UserId": "Larry@123",
"UserName": "Larry",
"UserPostDate": new ISODate('2019-03-27 12:00:00')
},
{
"UserId": "Sam@897",
"UserName": "Sam",
"UserPostDate": new ISODate('2012-06-17 11:40:30')
},
{
"UserId": "David@777",
"UserName": "David",
"UserPostDate": new ISODate('2018-01-31 10:45:35')
},
{
"UserId": "Chris@909",
"UserName": "Chris",
"UserPostDate": new ISODate('2017-04-14 04:12:04')
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c9a700f15e86fd1496b38ab"),
ObjectId("5c9a703815e86fd1496b38ac"),
ObjectId("5c9a705e15e86fd1496b38ad"),
ObjectId("5c9a708915e86fd1496b38ae")
]
}
Example 1: Find Oldest Post
db.getOldestAndYoungestPostDemo.find().sort({"UserPostDate": 1}).limit(1);
{
"_id": ObjectId("5c9a703815e86fd1496b38ac"),
"UserId": "Sam@897",
"UserName": "Sam",
"UserPostDate": ISODate("2012-06-17T11:40:30Z")
}
Example 2: Find Newest Post
db.getOldestAndYoungestPostDemo.find().sort({"UserPostDate": -1}).limit(1);
{
"_id": ObjectId("5c9a700f15e86fd1496b38ab"),
"UserId": "Larry@123",
"UserName": "Larry",
"UserPostDate": ISODate("2019-03-27T12:00:00Z")
}
Key Points
- sort(1) arranges dates in ascending order (oldest first)
- sort(-1) arranges dates in descending order (newest first)
- limit(1) returns only the first document from sorted results
Conclusion
Use sort() with limit(1) to efficiently find oldest or newest posts. Sort ascending for oldest, descending for newest, and limit to one result for optimal performance.
Advertisements
