หากต้องการจัดเรียงตามเอกสารย่อย ให้ใช้ $sort ใน MongoDB ให้เราสร้างคอลเลกชันที่มีเอกสาร -
> db.demo245.insertOne(
... {
... "_id": 101,
... "deatils": [
... { "DueDate": new ISODate("2019-01-10"), "Value": 45},
... {"DueDate": new ISODate("2019-11-10"), "Value": 34 }
... ]
... }
...);
{ "acknowledged" : true, "insertedId" : 101 }
> db.demo245.insertOne(
... {
... "_id": 102,
... "details": [
... { "DueDate": new ISODate("2019-12-11"), "Value": 29},
... {"DueDate": new ISODate("2019-03-10"), "Value": 78}
... ]
... }
...);
{ "acknowledged" : true, "insertedId" : 102 } แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -
> db.demo245.find();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{
"_id" : 101, "deatils" : [
{ "DueDate" : ISODate("2019-01-10T00:00:00Z"), "Value" : 45 },
{ "DueDate" : ISODate("2019-11-10T00:00:00Z"), "Value" : 34 }
]
}
{
"_id" : 102, "details" : [
{ "DueDate" : ISODate("2019-12-11T00:00:00Z"), "Value" : 29 },
{ "DueDate" : ISODate("2019-03-10T00:00:00Z"), "Value" : 78 } \
]
} ต่อไปนี้เป็นแบบสอบถามเพื่อจัดเรียงตามเอกสารย่อย -
> db.demo245.aggregate([
... { "$unwind": "$details" },
... { "$sort": { "_id": 1, "details.Value": -1 } },
... { "$group": {
... "_id": "$_id",
... "details": { "$push": "$details" }
... }},
... { "$sort": { "details.Value": -1 } }
...]) สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : 102, "details" : [ { "DueDate" : ISODate("2019-03-10T00:00:00Z"), "Value" : 78 }, { "DueDate" : ISODate("2019-12-11T00:00:00Z"), "Value" : 29 } ] }