Thuta Learning
ရှာဖွေရန်
AdvancedData & Databasesintermediate

MongoDB aggregate() and Aggregation Pipeline

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • Aggregation pipeline တည်ဆောက်ရန်
  • Stage အစီအစဉ်ကိုနားလည်ရန်
  • Group accumulator သုံးရန်

ရိုးရိုးလေး ရှင်းပြမယ်

Aggregation pipeline တွင် documents များသည် stage တစ်ခုစီကိုအစဉ်လိုက်ဖြတ်သန်းသည်။ $match ကိုအစောပိုင်းထား၍ data လျှော့ပြီး $group ဖြင့်အုပ်စုဖွဲ့တွက်ချက်နိုင်သည်။ aggregate() သည် $out သို့မဟုတ် $merge မပါလျှင် collection data ကိုမပြောင်းပါ။

javascript
db.orders.aggregate([
  { $match: { status: 'paid' } },
  {
    $group: {
      _id: '$customerId',
      orderCount: { $sum: 1 },
      totalSpent: { $sum: '$total' }
    }
  },
  { $match: { totalSpent: { $gte: 100000 } } },
  { $sort: { totalSpent: -1 } },
  { $project: { _id: 0, customerId: '$_id', orderCount: 1, totalSpent: 1 } }
])
You should see
{ customerId: 42, orderCount: 3, totalSpent: 185000 }

လက်တွေ့စမ်းကြည့်ရန်

products collection ကို category အလိုက် group လုပ်ပြီး average price နှင့် product count တွက်ပါ။

Aggregation PipelineMongoDB

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • $group ပြီးမှသာ filter အားလုံးလုပ်၍ documents မလိုအပ်ဘဲများစွာဖြတ်သန်းစေခြင်း
  • Field path ရှေ့တွင် $ မထည့်ခြင်း

လေ့ကျင့်ခန်း

products collection ကို category အလိုက် group လုပ်ပြီး average price နှင့် product count တွက်ပါ။

You'll know it worked when: { customerId: 42, orderCount: 3, totalSpent: 185000 }

MongoDB aggregate() and Aggregation Pipeline | Thuta Learning