AGGREGATION FRAMEWORK (DATABASE ADVANCE)

 AGGREGATION FRAMEWORK


1. Persiapan

  • Buka VSCode, open folder arahkan ke C:\xampp\htdocs dan view terminal - Buat direktori baru untuk proyek, misalnya crud-api2 
            mkdir crud-api4



            cd crud-api4

  • Inisialisasi npm untuk membuat file package.json:
            npm init -y



  • Instal semua dependency yang diperlukan:
            npm install express mongoose nodemon body-parser


  • Tambahkan script berikut di package.json untuk menjalankan aplikasi:
            "scripts": {
                "start": "node index.js",
                "dev": "nodemon index.js"
            }



  • Fungsi menambahkan script diatas agar ketika menjalankan server tidak manual dengan perintah seperti node index.js atau nodemon index.js tapi cukup dengan perintah npm run start atau npm run dev

2. Buat Database dan Koleksi

  • Buat database dengan nama: polibest4

  • Buat data koleksi customers dan isikan data berikut:
             [{ "_id": 1, "name": "John Doe", "email": "john@example.com", "phone": "555-1111" }, {                 "_id": 2, "name": "Jane Smith", "email": "jane@example.com", "phone": "555- 2222" }, {                 "_id": 3, "name": "Mike Brown", "email": "mike@example.com", "phone": "555- 3333" } ]


  • Buat data koleksi orders dan isikan data berikut:
[
{ "_id": 101, "order_date": "2024-10-01", "customer_id": 1, "products": [ { "name": "Laptop", "quantity": 1 }, { "name": "Mouse", "quantity": 2 } ], "amount": 1500 },
{ "_id": 102, "order_date": "2024-10-02", "customer_id": 2, "products": [ { "name": "Keyboard", "quantity": 1 } ], "amount": 100 },
{ "_id": 103, "order_date": "2024-10-03", "customer_id": 1, "products": [ { "name": "Monitor", "quantity": 1 } ], "amount": 300 },
{ "_id": 104, "order_date": "2024-10-04", "customer_id": 3, "products": [ { "name": "Phone", "quantity": 1 }, { "name": "Headphones", "quantity": 1 } ], "amount": 800 }
]



3. Buat File index.js

  • Buat file index.js di dalam folder crud-api4 dan isikan kode berikut:
const express = require('express'); const { MongoClient } = require('mongodb'); const app = express(); const port = 3000; const url = 'mongodb://localhost:27017'; const client = new MongoClient(url); const dbName = 'polibest4'; app.get('/orders/group', async (req, res) => { try { await client.connect(); const db = client.db(dbName); const ordersCollection = db.collection('orders'); // Agregasi dengan $group const result = await ordersCollection.aggregate([ { $group: { _id: "$customer_id", totalAmount: { $sum: "$amount" } } } ]).toArray(); res.json(result); } catch (err) { res.status(500).send('Error: ' + err.message); } finally { await client.close(); } }); app.get('/orders/match', async (req, res) => { try { await client.connect(); const db = client.db(dbName); const ordersCollection = db.collection('orders'); // Agregasi dengan $match dan $sort const result = await ordersCollection.aggregate([ { $match: { amount: { $gte: 300 } } }, { $sort: { amount: -1 } } ]).toArray(); res.json(result); } catch (err) { res.status(500).send('Error: ' + err.message); } finally { await client.close(); } }); app.get('/orders/lookup', async (req, res) => { try { await client.connect(); const db = client.db(dbName); const ordersCollection = db.collection('orders'); // $lookup - Joining orders and customers const result = await ordersCollection.aggregate([ { $lookup: { from: "customers", localField: "customer_id", foreignField: "_id", as: "customer_info" } } ]).toArray(); res.json(result); } catch (err) { res.status(500).send('Error: ' + err.message); } finally { await client.close(); } }); app.get('/orders/unwind', async (req, res) => { try { await client.connect(); const db = client.db(dbName); const ordersCollection = db.collection('orders'); // $unwind - Decompose products array const result = await ordersCollection.aggregate([ { $unwind: "$products" }, { $group: { _id: "$products.name", totalSold: { $sum: "$products.quantity" } } } ]).toArray(); res.json(result); } catch (err) { res.status(500).send('Error: ' + err.message); } finally { await client.close(); } }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}/`); });



4. Menjalankan dan Menguji Aplikasi dengan Agregasi Group

  • Jalankan server dengan perintah: npm run dev 


  • GET Request: http://localhost:3000/orders/group (Pada Aplikasi Postman)
  • Menampilkan jumlah total amount yang dibelanjakan oleh masing-masing customer_id.
  • Contoh output
[
{ "_id": 1, "totalAmount": 1800 },
{ "_id": 2, "totalAmount": 100 },
{ "_id": 3, "totalAmount": 800 }
]



5. Menjalankan dan Menguji Aplikasi dengan Agregasi Match

  • GET Request: http://localhost:3000/orders/match (Pada Aplikasi Postman)
  • Mengambil data pesanan dengan amount lebih besar dari atau sama dengan 300, lalu mengurutkan berdasarkan amount secara menurun (descending).
  • Contoh output:
[
{ "_id": 101, "order_date": "2024-10-01", "customer_id": 1, "products": [...], "amount": 1500 },
{ "_id": 104, "order_date": "2024-10-04", "customer_id": 3, "products": [...], "amount": 800 },
{ "_id": 103, "order_date": "2024-10-03", "customer_id": 1, "products": [...], "amount": 300 }
]





6. Menjalankan dan Menguji Aplikasi dengan Agregasi Lookup

  • GET Request: http://localhost:3000/orders/lookup (Pada Aplikasi Postman)

  • This endpoint will join the orders collection with the customers collection, displaying customer information along with each order. 
  • Contoh output:
{
    "_id": 101,
    "order_date": "2024-10-01",
    "customer_id": 1,
    "products": [...],
    "amount": 1500,
    "customer_info": [
        { "_id": 1, "name": "John Doe", "email": "john@example.com" }
    ]
}


7. Menjalankan dan Menguji Aplikasi dengan Agregasi Unwind

  • GET Request: http://localhost:3000/orders/unwind


  • This endpoint will decompose the products array from the orders collection and group them by product name with the total quantity sold.
  • Contoh output:
            { "_id": "Laptop", "totalSold": 1 }
            { "_id": "Mouse", "totalSold": 2 }




8. Tugas

  • Jalankan ke-4 aggregate diatas dengan MongoDB Shell dan screenshot hasil
  • Klik pada koleksi orders untuk melihat data.
  • Di bagian atas, klik tab Aggregation untuk membuka fitur agregasi.
  • Klik pada menu "Open MongoDB shell" pada bagian kanan atas
  • Lalu Masukkan Code dibawah ini
  • Dan akan keluar output seperti dibawah ini

Agregasi Group



Agregasi Match



Agregasi Lookup



Agregasi Unwind



  • Jalankan ke-4 aggregate diatas dengan MongoDB Compass dan screenshot hasil
  • Klik pada koleksi orders untuk melihat data.
  • Di bagian atas, klik tab Aggregation untuk membuka fitur agregasi.
  • Di editor pipeline, kamu bisa menuliskan query agregasi satu per satu untuk setiap tugas agregasi yang diminta (Group, Match, Lookup, dan Unwind).
  • Lalu Masukkan Code dibawah ini
  • Dan akan keluar output seperti dibawah ini

Agregasi Group



Agregasi Match



Agregasi Lookup



Agregasi Unwind





TERIMAKASIH



Komentar

Postingan populer dari blog ini

TUTORIAL ERP ODOO (ENTERPRISE RESOURCE PLANNING)

LOCAL/REMOTE FILE INCLUSION (DASAR KEMANAN SIBER)

OSINT (DASAR KEAMANAN SIBER)