ใช้ Aggregation Framework คำนวณผลรวมด้วย $add แล้วเรียงลำดับด้วย $sort
ตัวอย่างการใช้งาน
สร้างคอลเลกชันพร้อมข้อมูล:
> db.orderByTwoFieldsDemo.insertOne({"Value1":10,"Value2":35});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca285576304881c5ce84baa") }
> db.orderByTwoFieldsDemo.insertOne({"Value1":12,"Value2":5});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca2855f6304881c5ce84bab") }
> db.orderByTwoFieldsDemo.insertOne({"Value1":55,"Value2":65});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca285686304881c5ce84bac") }
แสดงเอกสารทั้งหมด:
> db.orderByTwoFieldsDemo.find().pretty();
ผลลัพธ์:
กรณีที่ 1: เรียงตามผลรวมน้อยไปมาก (Ascending)
ผลลัพธ์:
กรณีที่ 2: เรียงตามผลรวมมากไปน้อย (Descending)
ผลลัพธ์:
สรุป: ใช้
$projectสร้างฟิลด์ใหม่เก็บผลรวม$add: ["$field1", "$field2"]แล้ว$sortตามฟิลด์ใหม่นั้น