ခဏလေး ဒီလိုပဲ စဉ်းစားကြည့်
Application တစ်ခုမှာ data အရေအတွက် တိုးလာတဲ့အခါ query speed ကို ထိန်းရန် index လိုအပ်လာပါတယ်။ ဒါ့အပြင် task list တစ်ခုတည်းပြင်ရုံမက status အလိုက် task ဘယ်နှစ်ခုရှိလဲ၊ priority အလိုက် ဘယ်လောက်ရှိလဲဆိုတာကို summarize ပြသဖို့ dashboard/report feature တစ်ခုကိုလည်း app တော်တော်များများမှာ လိုအပ်ပါတယ်။ ဒီအဆင့်မှာ frequently-queried field ဖြစ်တဲ့ status field ပေါ်မှာ index တည်ဆောက်ပြီး $match နဲ့ $group ပါဝင်တဲ့ aggregation pipeline တစ်ခုကို ရေးကာ status အလိုက် task count summary report ထုတ်ကြည့်ပါမယ်။ ဒါက Basic chapter ကနေ Advanced chapter အထိ လေ့လာထားတဲ့ concept တွေအားလုံးကို project တစ်ခုတည်းအောက်မှာ ပေါင်းစပ်အသုံးချတာ ဖြစ်ပါတယ်။
လက်တွေ့ ဆောက်ကြည့်မယ်
status field ပေါ်မှာ createIndex({ status: 1 }) နဲ့ ascending index တစ်ခု တည်ဆောက်ပါ — status ကို filter လုပ်တဲ့ query တွေ ပိုမြန်လာမှာဖြစ်ပါတယ်။ ပြီးရင် aggregate() pipeline တစ်ခုကို ရေးပါ — $match stage နဲ့ priority: "high" ဖြစ်တဲ့ task တွေကိုပဲ ရွေးပြီး၊ $group stage နဲ့ status field ကို _id အဖြစ်ယူကာ task count ကို $sum: 1 ဖြင့် စုစည်းပါ၊ နောက်ဆုံး $sort stage ကို ထည့်ပြီး result ကို count အများကနေ အနည်းသို့ စီပါ။ Pipeline ရလဒ်ကနေ status အလိုက် high-priority task ဘယ်နှစ်ခုရှိလဲဆိုတာကို summary report တစ်ခုအနေနဲ့ ရရှိမှာဖြစ်ပြီး ဒါဟာ project ရဲ့ နောက်ဆုံးအဆင့်ပါပဲ။
Code နမူနာ
// status field ပေါ်မှာ index တည်ဆောက်ပါ (query speed အတွက်)
db.tasks.createIndex({ status: 1 })
// index list ကို confirm လုပ်ကြည့်ပါ
db.tasks.getIndexes()
// priority: high task များကို status အလိုက် count လုပ်၍ report ထုတ်ပါ
db.tasks.aggregate([
{ $match: { priority: "high" } },
{ $group: { _id: "$status", total: { $sum: 1 } } },
{ $sort: { total: -1 } }
])aggregate() pipeline run ပြီးတိုင်း { _id: "pending", total: 2 }, { _id: "completed", total: 1 } စတဲ့ status အလိုက် count summary document များကို ပြန်ပေးမည်။၅ မိနစ် စမ်းကြည့်
$group stage ကို priority field နဲ့ ပြောင်းရေးပြီး priority အလိုက် task count summary report ကိုပါ ထပ်ထုတ်ကြည့်ပါ — ၅ မိနစ်အတွင်း pipeline ကို ပြင်ပြီး run လုပ်ကြည့်ပါ။
သတိလေးတစ်ချက်
Aggregation pipeline ရေးတဲ့အခါ $match stage ကို ဖြစ်နိုင်သမျှ pipeline ရဲ့ အစောပိုင်းမှာ ထားပါ — document အရေအတွက်ကို အစောကတည်းက လျှော့ချနိုင်လျှင် pipeline တစ်ခုလုံး ပိုမြန်ပါတယ်။