🎓 Get Full Quality Study Materials & Lab Manuals — Follow our blog using the button below!  |  📺 Subscribe our YouTube Channel "Lectures by Ravula Govardhan" for Programming Contents!  | 
● NEW Experiment 1 to 13 Full Stack Development Lab Programs available Read it here →
“à°ˆ à°°ోà°œు à°¨ేà°°్à°šుà°•ుà°¨్à°¨ à°šిà°¨్à°¨ à°µిà°·à°¯ం, à°°ేపటి à°ªెà°¦్à°¦ à°µిజయాà°¨ిà°•ి à°ªుà°¨ాà°¦ి.”

Sales Report System using MongoDB Aggregation | $group $sum $avg Lab

Experiment · MongoDB Lab

Sales Report System using MongoDB Aggregation

Aim

To create a simple Sales Report System using Node.js, Express.js, and MongoDB that demonstrates Aggregation Operations: $group, $sum, and $avg.

Software Requirements

  • Node.js
  • VS Code
  • MongoDB
  • Web Browser
01 Project structure

Create a folder and open it in VS Code. The final structure looks like this:

sales-report/
│
├── server.js
├── package.json
│
└── public/
    └── index.html
02 Install the required packages
Terminal
npm init -y
npm install express mongoose
03 Create server.js

This file connects to MongoDB, stores sample sales data, and creates three simple aggregation reports using $sum, $group, and $avg.

server.js
const express = require('express');
const mongoose = require('mongoose');

const app = express();
app.use(express.json());
app.use(express.static('public'));

// Connect MongoDB
mongoose.connect('mongodb://127.0.0.1:27017/salesDB')
  .then(() => console.log('MongoDB Connected'))
  .catch(err => console.log(err));

// Schema
const saleSchema = new mongoose.Schema({
  product: String,
  category: String,
  amount: Number
});

const Sale = mongoose.model('Sale', saleSchema);

// ========== ROUTES ==========

// Add Sample Data
app.post('/add', async (req, res) => {
  await Sale.deleteMany({});

  await Sale.insertMany([
    { product: 'Laptop', category: 'Electronics', amount: 50000 },
    { product: 'Mobile', category: 'Electronics', amount: 20000 },
    { product: 'Shirt', category: 'Clothing', amount: 1000 },
    { product: 'Jeans', category: 'Clothing', amount: 1500 },
    { product: 'Book', category: 'Stationery', amount: 300 },
    { product: 'Pen', category: 'Stationery', amount: 50 },
    { product: 'Laptop', category: 'Electronics', amount: 55000 },
    { product: 'Mobile', category: 'Electronics', amount: 18000 }
  ]);

  res.json({ message: 'Sample data added' });
});

// 1. Total Sales (Using $sum)
app.get('/total', async (req, res) => {
  const result = await Sale.aggregate([
    {
      $group: {
        _id: null,
        totalSales: { $sum: '$amount' }
      }
    }
  ]);
  res.json(result[0]);
});

// 2. Sales by Category (Using $group + $sum)
app.get('/category', async (req, res) => {
  const result = await Sale.aggregate([
    {
      $group: {
        _id: '$category',
        total: { $sum: '$amount' }
      }
    }
  ]);
  res.json(result);
});

// 3. Average Sales (Using $avg)
app.get('/average', async (req, res) => {
  const result = await Sale.aggregate([
    {
      $group: {
        _id: null,
        averageSales: { $avg: '$amount' }
      }
    }
  ]);
  res.json(result[0]);
});

app.listen(5000, () => {
  console.log('Server running on http://localhost:5000');
});
04 Create public/index.html

A simple front-end with three report buttons and one button to add sample data.

public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Sales Report System</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      background: #f4f6f9;
      padding: 40px 20px;
    }
    .container {
      max-width: 600px;
      margin: auto;
    }
    h1 {
      text-align: center;
      margin-bottom: 10px;
    }
    p {
      text-align: center;
      color: #666;
      margin-bottom: 30px;
    }
    .card {
      background: white;
      padding: 25px;
      border-radius: 12px;
      margin-bottom: 20px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.08);
    }
    button {
      background: #1e293b;
      color: white;
      border: none;
      padding: 10px 16px;
      margin: 5px;
      border-radius: 6px;
      cursor: pointer;
    }
    button:hover {
      background: #0f172a;
    }
    .green {
      background: #059669;
    }
    #result {
      background: #f8fafc;
      padding: 15px;
      border-radius: 8px;
      font-family: monospace;
      white-space: pre-wrap;
      min-height: 80px;
    }
  </style>
</head>
<body>

  <div class="container">
    <h1>Sales Report System</h1>
    <p>MongoDB Aggregation: $group, $sum, $avg</p>

    <div class="card">
      <h3>1. Setup</h3>
      <button class="green" onclick="addData()">Add Sample Data</button>
    </div>

    <div class="card">
      <h3>2. Reports</h3>
      <button onclick="getTotal()">Total Sales ($sum)</button>
      <button onclick="getCategory()">Sales by Category ($group)</button>
      <button onclick="getAverage()">Average Sales ($avg)</button>
    </div>

    <div class="card">
      <h3>Result</h3>
      <pre id="result">Click a button to see result...</pre>
    </div>
  </div>

  <script>
    async function addData() {
      const res = await fetch('/add', { method: 'POST' });
      const data = await res.json();
      show(data);
    }

    async function getTotal() {
      const res = await fetch('/total');
      const data = await res.json();
      show(data);
    }

    async function getCategory() {
      const res = await fetch('/category');
      const data = await res.json();
      show(data);
    }

    async function getAverage() {
      const res = await fetch('/average');
      const data = await res.json();
      show(data);
    }

    function show(data) {
      document.getElementById('result').innerText = JSON.stringify(data, null, 2);
    }
  </script>

</body>
</html>
05 Run the application

Start MongoDB, then run:

Terminal
node server.js

You should see:

MongoDB Connected
Server running on http://localhost:5000
06 Open the application

In your browser go to:

http://localhost:5000
07 How to test
  1. Click Add Sample Data first.
  2. Click Total Sales ($sum) to see total revenue.
  3. Click Sales by Category ($group) to see grouped totals.
  4. Click Average Sales ($avg) to see the average amount.

What Students Will Learn

Button Operator Meaning
Total Sales $sum Add all sales amounts
Sales by Category $group Group data by category
Average Sales $avg Find average of all amounts

Example Output

Total Sales:

{ "totalSales": 145850 }

Sales by Category:

[
  { "_id": "Electronics", "total": 143000 },
  { "_id": "Clothing", "total": 2500 },
  { "_id": "Stationery", "total": 350 }
]

Result: The Sales Report System successfully demonstrates MongoDB Aggregation Operations ($group, $sum, $avg) for generating simple and useful sales reports.

Node.js Express.js MongoDB Aggregation $group $sum $avg

0 Ravula Kartheek:

Post a Comment