ใช้ sort() ร่วมกับ limit(1) เพื่อหาเอกสารที่มีวันที่เก่าสุด (Oldest) หรือใหม่สุด (Youngest/Recent)
รูปแบบคำสั่ง
// เก่าสุด (Oldest) - เรียง ASC (1)
db.collection.find().sort({ "dateField": 1 }).limit(1);
// ใหม่สุด (Youngest/Recent) - เรียง DESC (-1)
db.collection.find().sort({ "dateField": -1 }).limit(1);
ตัวอย่างเต็มรูปแบบ
1. สร้างข้อมูลตัวอย่าง (มี UserPostDate)
> db.getOldestAndYoungestPostDemo.insertOne({ "UserId": "Larry@123", "UserName": "Larry", "UserPostDate": new ISODate('2019-03-27 12:00:00') });
> db.getOldestAndYoungestPostDemo.insertOne({ "UserId": "Sam@897", "UserName": "Sam", "UserPostDate": new ISODate('2012-06-17 11:40:30') });
> db.getOldestAndYoungestPostDemo.insertOne({ "UserId": "David@777", "UserName": "David", "UserPostDate": new ISODate('2018-01-31 10:45:35') });
> db.getOldestAndYoungestPostDemo.insertOne({ "UserId": "Chris@909", "UserName": "Chris", "UserPostDate": new ISODate('2017-04-14 04:12:04') });
2. แสดงข้อมูลทั้งหมด
> db.getOldestAndYoungestPostDemo.find().pretty();
{ "_id" : ..., "UserId" : "Larry@123", "UserName" : "Larry", "UserPostDate" : ISODate("2019-03-27T12:00:00Z") }
{ "_id" : ..., "UserId" : "Sam@897", "UserName" : "Sam", "UserPostDate" : ISODate("2012-06-17T11:40:30Z") }
{ "_id" : ..., "UserId" : "David@777", "UserName" : "David", "UserPostDate" : ISODate("2018-01-31T10:45:35Z") }
{ "_id" : ..., "UserId" : "Chris@909", "UserName" : "Chris", "UserPostDate" : ISODate("2017-04-14T04:12:04Z") }
3. หาโพสต์เก่าสุด (Oldest)
> db.getOldestAndYoungestPostDemo.find().sort({ "UserPostDate": 1 }).limit(1);
{ "_id" : ..., "UserId" : "Sam@897", "UserName" : "Sam", "UserPostDate" : ISODate("2012-06-17T11:40:30Z") }
4. หาโพสต์ใหม่สุด (Youngest/Recent)
> db.getOldestAndYoungestPostDemo.find().sort({ "UserPostDate": -1 }).limit(1);
{ "_id" : ..., "UserId" : "Larry@123", "UserName" : "Larry", "UserPostDate" : ISODate("2019-03-27T12:00:00Z") }
เคล็ดลับประสิทธิภาพ
- สร้าง Index บนฟิลด์วันที่:
db.collection.createIndex({ "UserPostDate": 1 }) - Index ช่วยให้ sort + limit เร็วมาก (ไม่ต้อง scan ทุกเอกสาร)
- ใช้
ISODate()หรือnew Date()สำหรับเก็บวันที่ (ไม่ใช่ string)
สรุป
sort({ dateField: 1 }).limit(1)= เก่าสุด (Ascending)sort({ dateField: -1 }).limit(1)= ใหม่สุด (Descending)- ต้องเก็บวันที่เป็น Date type (ISODate) ไม่ใช่ String
- ควรสร้าง Index บนฟิลด์วันที่สำหรับ Production