หากต้องการค้นหาโพสต์ที่เก่าที่สุด/อายุน้อยที่สุดในคอลเล็กชัน MongoDB คุณสามารถใช้ sort() สมมติว่าคุณมีเอกสารที่มีฟิลด์ "UserPostDate" และคุณต้องได้รับโพสต์ที่เก่าที่สุดและอายุน้อยที่สุด เพื่อที่ ให้เราสร้างคอลเลกชันที่มีเอกสารก่อน
>db.getOldestAndYoungestPostDemo.insertOne({"UserId":"Larry@123","UserName":"Larry","UserPostDate":new ISODate('2019-03-27 12:00:00')});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9a700f15e86fd1496b38ab")
}
>db.getOldestAndYoungestPostDemo.insertOne({"UserId":"Sam@897","UserName":"Sam","UserPostDate":new ISODate('2012-06-17 11:40:30')});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9a703815e86fd1496b38ac")
}
>db.getOldestAndYoungestPostDemo.insertOne({"UserId":"David@777","UserName":"David","UserPostDate":new ISODate('2018-01-31 10:45:35')});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9a705e15e86fd1496b38ad")
}
>db.getOldestAndYoungestPostDemo.insertOne({"UserId":"Chris@909","UserName":"Chris","UserPostDate":new ISODate('2017-04-14 04:12:04')});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9a708915e86fd1496b38ae")
} ต่อไปนี้เป็นแบบสอบถามเพื่อแสดงเอกสารทั้งหมดจากคอลเลกชันโดยใช้วิธี find()
> db.getOldestAndYoungestPostDemo.find().pretty();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้
{
"_id" : ObjectId("5c9a700f15e86fd1496b38ab"),
"UserId" : "Larry@123",
"UserName" : "Larry",
"UserPostDate" : ISODate("2019-03-27T12:00:00Z")
}
{
"_id" : ObjectId("5c9a703815e86fd1496b38ac"),
"UserId" : "Sam@897",
"UserName" : "Sam",
"UserPostDate" : ISODate("2012-06-17T11:40:30Z")
}
{
"_id" : ObjectId("5c9a705e15e86fd1496b38ad"),
"UserId" : "David@777",
"UserName" : "David",
"UserPostDate" : ISODate("2018-01-31T10:45:35Z")
}
{
"_id" : ObjectId("5c9a708915e86fd1496b38ae"),
"UserId" : "Chris@909",
"UserName" : "Chris",
"UserPostDate" : ISODate("2017-04-14T04:12:04Z")
} ต่อไปนี้เป็นแบบสอบถามเพื่อค้นหาโพสต์ที่เก่าที่สุดในคอลเลกชัน MongoDB
> db.getOldestAndYoungestPostDemo.find().sort({ "UserPostDate" : 1 }).limit(1); สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้
{ "_id" : ObjectId("5c9a703815e86fd1496b38ac"), "UserId" : "Sam@897", "UserName" : "Sam", "UserPostDate" : ISODate("2012-06-17T11:40:30Z") } ต่อไปนี้เป็นข้อความค้นหาเพื่อค้นหาโพสต์ที่อายุน้อยที่สุด (ล่าสุด) ในคอลเล็กชัน MongoDB
> db.getOldestAndYoungestPostDemo.find().sort({ "UserPostDate" : -1 }).limit(1); สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้
{ "_id" : ObjectId("5c9a700f15e86fd1496b38ab"), "UserId" : "Larry@123", "UserName" : "Larry", "UserPostDate" : ISODate("2019-03-27T12:00:00Z") }