Devdit
 

MongoDB order by ยังไง แบบ asc desc

805

MongoDB order by ยังไง แบบ asc desc บทความนี้สอนใช้คำสั่ง sort ร่วมกับตัวเลข 1 และ -1 ถ้า 1 = asc คือน้อยไปมาก ถ้า -1 = desc คือมากไปน้อย พร้อมแสดงผลลัพธ์ออกสู่หน้าจอ สามารถเขียนคำสั่งได้ดังนี้

 

ตัวอย่าง MongoDB order by ยังไง แบบ asc

db.product.find( {}, {_id:0} ).sort( {price:1} )

ผลลัพธ์

{ name: 'Mouse', price: 100 }
{ name: 'MongoDB', price: 180 }
{ name: 'Notebook', price: 200 }
{ name: 'Computer', price: 200 }
{ name: 'Mobile', price: 220 }
{ name: 'Super Computer', price: 400 }

คำอธิบาย

จากตัวอย่างใช้คำสั่ง sort( {price:1} ) คือเรียงลำดับข้อมูลจาก field price แบบน้อยไปมาก หรือ asc

 

ตัวอย่าง MongoDB order by ยังไง แบบ desc

db.product.find( {}, {_id:0} ).sort( {price:-1} )

ผลลัพธ์

{ name: 'Super Computer', price: 400 }
{ name: 'Mobile', price: 220 }
{ name: 'Notebook', price: 200 }
{ name: 'Computer', price: 200 }
{ name: 'MongoDB', price: 180 }
{ name: 'Mouse', price: 100 }

คำอธิบาย

จากตัวอย่างใช้คำสั่ง sort( {price:-1} ) คือเรียงลำดับข้อมูลจาก field price แบบมากไปน้อย หรือ desc

แก้ไข 1 ปีที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ