วิธีง่ายที่สุดในการเรียงลำดับอาร์เรย์ใน MongoDB คือใช้ $sort ร่วมกับ $unwind และ $group ใน Aggregation Pipeline
สร้างคอลเลกชันพร้อมเอกสารที่มีอาร์เรย์รายละเอียด:
> db.demo242.insertOne(
... {"details2":
... [
... {"ShipingDate":new ISODate("2019-10-11"),"Price":1400},
... {"ShipingDate":new ISODate("2019-10-01"),"Price":1600 }
... ]
... }
...);
{ "acknowledged" : true, "insertedId" : ObjectId("5e4429229af932883c61ea44") }
แสดงเอกสารทั้งหมด:
> db.demo242.find();
ผลลัพธ์ - อาร์เรย์ยังไม่ได้เรียงลำดับ:
{
"_id" : ObjectId("5e4429229af932883c61ea44"),
"details2" : [
{ "ShipingDate" : ISODate("2019-10-11T00:00:00Z"), "Price" : 1400 },
{ "ShipingDate" : ISODate("2019-10-01T00:00:00Z"), "Price" : 1600 }
]
}
คำสั่ง Aggregation สำหรับเรียงลำดับอาร์เรย์ตาม ShipingDate (จากน้อยไปมาก):
> db.demo242.aggregate([
{$unwind: "$details2"},
{$sort: {"details2.ShipingDate":1}},
{$group: {_id:"$_id", details2: {$push:"$details2.ShipingDate"}}}
]);
ผลลัพธ์ - อาร์เรย์ถูกเรียงลำดับตามวันที่จากเก่าสุดไปใหม่สุด:
{
"_id" : ObjectId("5e4429229af932883c61ea44"),
"details2" : [
ISODate("2019-10-01T00:00:00Z"),
ISODate("2019-10-11T00:00:00Z")
]
}