ใช้ sort() หลัง find() เพื่อจัดเรียงผลลัพธ์ ตัวเลข 1 = ขึ้น (A-Z, น้อยไปมาก), -1 = ลง (Z-A, มากไปน้อย)
ตัวอย่างข้อมูลทดสอบ
> db.demo32.insertOne({"Name":"Chris"});
> db.demo32.insertOne({"Name":"Bob"});
> db.demo32.insertOne({"Name":"Adam"});
> db.demo32.insertOne({"Name":"John"});
> db.demo32.insertOne({"Name":"Carol"});
แสดงข้อมูลก่อนจัดเรียง
> db.demo32.find();
{
"_id" : ObjectId("5e175158cfb11e5c34d898c5"), "Name" : "Chris"
}
{
"_id" : ObjectId("5e17515ccfb11e5c34d898c6"), "Name" : "Bob"
}
{
"_id" : ObjectId("5e175160cfb11e5c34d898c7"), "Name" : "Adam"
}
{
"_id" : ObjectId("5e175165cfb11e5c34d898c8"), "Name" : "John"
}
{
"_id" : ObjectId("5e17517bcfb11e5c34d898c9"), "Name" : "Carol"
}
คำสั่งจัดเรียง A-Z
> db.demo32.find().sort({"Name":1});
ผลลัพธ์
{
"_id" : ObjectId("5e175160cfb11e5c34d898c7"), "Name" : "Adam"
}
{
"_id" : ObjectId("5e17515ccfb11e5c34d898c6"), "Name" : "Bob"
}
{
"_id" : ObjectId("5e17517bcfb11e5c34d898c9"), "Name" : "Carol"
}
{
"_id" : ObjectId("5e175158cfb11e5c34d898c5"), "Name" : "Chris"
}
{
"_id" : ObjectId("5e175165cfb11e5c34d898c8"), "Name" : "John"
}
หมายเหตุ: สร้างดัชนี (index) บนฟิลด์ที่ sort บ่อยเพื่อเพิ่มประสิทธิภาพ: db.demo32.createIndex({"Name":1})