Thuta Learning
MongoDB
AdvancedData & Databasesအလယ်အလတ်

MongoDB aggregate() and Aggregation Pipeline

MongoDBသင်ခန်းစာ 18

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

  • 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 Pipeline — MongoDB

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

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

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

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

အလုပ်ဖြစ်ကြောင်း ဒီလိုသိမယ်: { customerId: 42, orderCount: 3, totalSpent: 185000 }

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

MongoDB aggregate() and Aggregation Pipeline | Thuta Learning