Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

จัดเรียงเอกสาร MongoDB 昇順 (Ascending) ด้วย Aggregation $sort

ใช้ขั้นตอน $sort ใน Aggregation Pipeline เพื่อจัดเรียงเอกสาร ตัวอย่างนี้รวมถึงการ unwind อาร์เรย์ก่อนจัดเรียง

> db.demo652.insertOne({
...   value: 10,
...   "details": [
...     {"ProductName": "Product-1", "ProductQuantity": 8, "ProductPrice": 500},
...     {"ProductName": "Product-2", "ProductQuantity": 7, "ProductPrice": 500}
...   ]
... });
{ "acknowledged" : true, "insertedId" : ObjectId("5e9f0730e3c3cd0dcff36a62") }
> db.demo652.insertOne({
...   value: 5,
...   "details": [
...     {"ProductName": "Product-1", "ProductQuantity": 8, "ProductPrice": 500},
...     {"ProductName": "Product-2", "ProductQuantity": 7, "ProductPrice": 500}
...   ]
... });
{ "acknowledged" : true, "insertedId" : ObjectId("5e9f0740e3c3cd0dcff36a63") }

แสดงข้อมูล:

> db.demo652.find();
{ "_id" : ObjectId("5e9f0730e3c3cd0dcff36a62"), "value" : 10, "details" : [ { "ProductName" : "Product-1", "ProductQuantity" : 8, "ProductPrice" : 500 }, { "ProductName" : "Product-2", "ProductQuantity" : 7, "ProductPrice" : 500 } ] }
{ "_id" : ObjectId("5e9f0740e3c3cd0dcff36a63"), "value" : 5, "details" : [ { "ProductName" : "Product-1", "ProductQuantity" : 8, "ProductPrice" : 500 }, { "ProductName" : "Product-2", "ProductQuantity" : 7, "ProductPrice" : 500 } ] }

คิวรี Aggregation จัดเรียงตาม value (ProductPrice ในตัวอย่าง) 昇順

> db.demo652.aggregate([
...   { "$unwind": "$details" },
...   { "$match": {} },
...   { "$group": {
...     "ProductPrice": { "$first": "$value" },
...     "details": { "$push": { "ProductName": "$details.ProductName" } },
...     "_id": "$_id"
...   }},
...   { "$sort": { "ProductPrice": 1 } },
...   { "$project": { "_id": 0, "ProductPrice": 1, "details": 1 } }
... ]).pretty();

ผลลัพธ์ - เรียงจาก value 5 แล้ว 10:

{ "ProductPrice" : 5, "details" : [ { "ProductName" : "Product-1" }, { "ProductName" : "Product-2" } ] }
{ "ProductPrice" : 10, "details" : [ { "ProductName" : "Product-1" }, { "ProductName" : "Product-2" } ] }

คำอธิบาย

  • $unwind: แยกอาร์เรย์ details (แม้ในตัวอย่างจะไม่จำเป็นก็ได้)
  • $group: รวมกลับ โดยดึง value มาเป็น ProductPrice
  • $sort: {ProductPrice: 1}: เรียงขึ้น (1 = ascending, -1 = descending)
  • $project: จัดรูปแบบ output

หมายเหตุ: $sort ควรวางหลัง $match/$limit เพื่อลดข้อมูลที่ต้อง sort (performance)