🎓 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 →
“à°ˆ à°°ోà°œు à°¨ేà°°్à°šుà°•ుà°¨్à°¨ à°šిà°¨్à°¨ à°µిà°·à°¯ం, à°°ేపటి à°ªెà°¦్à°¦ à°µిజయాà°¨ిà°•ి à°ªుà°¨ాà°¦ి.”

Student Records System using MongoDB Query Operators | Node.js Express Lab

Experiment · MongoDB Lab

Student Records System using MongoDB Query Operators

Aim

To create a simple Student Records System using Node.js, Express.js, and MongoDB that demonstrates the working of important MongoDB Query Operators such as $eq, $gt, $lt, $and, and $or.

Software Requirements

  • Node.js
  • VS Code
  • MongoDB Community Server
  • MongoDB Compass (optional)
  • Web Browser
01 Create the project

Open VS Code and create a folder named student-system, then open that folder. The final project structure looks like this:

student-system/
│
├── server.js
├── index.html
└── package.json
02 Install the required packages

Open the VS Code terminal and run:

Terminal
npm init -y

Then install the required packages:

Terminal
npm install express mongoose cors
03 Create server.js

This file connects to MongoDB, defines the Student schema, and creates routes for adding students and demonstrating MongoDB Query Operators.

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

const app = express();
app.use(cors());
app.use(express.json());
app.use(express.static(__dirname));

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

// Student Schema
const studentSchema = new mongoose.Schema({
  name: String,
  age: Number,
  department: String,
  cgpa: Number
});

const Student = mongoose.model('Student', studentSchema);

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

// Add Student
app.post('/add', async (req, res) => {
  try {
    const student = new Student(req.body);
    await student.save();
    res.json({ message: 'Student Added Successfully', student });
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

// Get All Students
app.get('/all', async (req, res) => {
  const students = await Student.find();
  res.json(students);
});

// $eq → Equal to
app.get('/eq/:dept', async (req, res) => {
  const students = await Student.find({ department: { $eq: req.params.dept } });
  res.json(students);
});

// $gt → Greater than
app.get('/gt/:cgpa', async (req, res) => {
  const students = await Student.find({ cgpa: { $gt: Number(req.params.cgpa) } });
  res.json(students);
});

// $lt → Less than
app.get('/lt/:age', async (req, res) => {
  const students = await Student.find({ age: { $lt: Number(req.params.age) } });
  res.json(students);
});

// $and → Multiple conditions
app.get('/and', async (req, res) => {
  const students = await Student.find({
    $and: [
      { department: 'CSE' },
      { cgpa: { $gte: 8 } }
    ]
  });
  res.json(students);
});

// $or → Any condition
app.get('/or', async (req, res) => {
  const students = await Student.find({
    $or: [
      { department: 'CSE' },
      { cgpa: { $gt: 9 } }
    ]
  });
  res.json(students);
});

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

This is the front-end page. It has a form to add students and buttons to test different MongoDB Query Operators.

index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Student Records System</title>
  <style>
    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }
    body {
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      background-color: #f0f2f5;
      color: #333;
      line-height: 1.5;
    }
    .header {
      background-color: #1e3a5f;
      color: white;
      padding: 20px;
      text-align: center;
    }
    .header h1 {
      font-size: 24px;
      margin-bottom: 5px;
    }
    .header p {
      font-size: 14px;
      opacity: 0.9;
    }
    .container {
      max-width: 800px;
      margin: 30px auto;
      padding: 0 15px;
    }
    .card {
      background: white;
      border-radius: 8px;
      padding: 25px;
      margin-bottom: 25px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.08);
    }
    .card h2 {
      font-size: 18px;
      margin-bottom: 15px;
      color: #1e3a5f;
      border-bottom: 2px solid #e0e0e0;
      padding-bottom: 8px;
    }
    .form-group {
      margin-bottom: 15px;
    }
    label {
      display: block;
      font-size: 14px;
      margin-bottom: 5px;
      color: #555;
    }
    input {
      width: 100%;
      padding: 10px 12px;
      border: 1px solid #ccc;
      border-radius: 5px;
      font-size: 15px;
    }
    input:focus {
      outline: none;
      border-color: #1e3a5f;
    }
    .btn {
      background-color: #1e3a5f;
      color: white;
      border: none;
      padding: 10px 18px;
      border-radius: 5px;
      font-size: 15px;
      cursor: pointer;
      margin-top: 5px;
    }
    .btn:hover {
      background-color: #16304f;
    }
    .btn-group {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      margin-top: 10px;
    }
    .btn-query {
      background-color: #2c7a4b;
      padding: 9px 14px;
      font-size: 14px;
    }
    .btn-query:hover {
      background-color: #23633c;
    }
    #result {
      background-color: #fafafa;
      border: 1px solid #e0e0e0;
      border-radius: 5px;
      padding: 15px;
      margin-top: 15px;
      min-height: 100px;
      font-family: Consolas, monospace;
      font-size: 14px;
      white-space: pre-wrap;
      overflow-x: auto;
    }
    .note {
      font-size: 13px;
      color: #666;
      margin-top: 10px;
    }
    .footer {
      text-align: center;
      padding: 20px;
      font-size: 13px;
      color: #777;
    }
  </style>
</head>
<body>

  <div class="header">
    <h1>Student Records System</h1>
    <p>Using MongoDB Query Operators | Node.js + Express + MongoDB</p>
  </div>

  <div class="container">

    <!-- Add Student Section -->
    <div class="card">
      <h2>Add New Student</h2>

      <div class="form-group">
        <label>Student Name</label>
        <input type="text" id="name" placeholder="Enter full name">
      </div>

      <div class="form-group">
        <label>Age</label>
        <input type="number" id="age" placeholder="Enter age">
      </div>

      <div class="form-group">
        <label>Department</label>
        <input type="text" id="department" placeholder="CSE / IT / ECE">
      </div>

      <div class="form-group">
        <label>CGPA</label>
        <input type="number" id="cgpa" placeholder="Example: 8.5" step="0.1">
      </div>

      <button class="btn" onclick="addStudent()">Add Student</button>
      <p class="note">Fill all fields and click Add Student</p>
    </div>

    <!-- Query Section -->
    <div class="card">
      <h2>MongoDB Query Operators</h2>
      <p style="margin-bottom: 15px; color: #555; font-size: 14px;">
        Click any button below to see how different MongoDB operators work.
      </p>

      <div class="btn-group">
        <button class="btn btn-query" onclick="getAll()">Get All Students</button>
        <button class="btn btn-query" onclick="getEQ()">$eq → Department = CSE</button>
        <button class="btn btn-query" onclick="getGT()">$gt → CGPA > 8</button>
        <button class="btn btn-query" onclick="getLT()">$lt → Age < 21</button>
        <button class="btn btn-query" onclick="getAND()">$and → CSE + CGPA ≥ 8</button>
        <button class="btn btn-query" onclick="getOR()">$or → CSE or CGPA > 9</button>
      </div>

      <h3 style="margin-top: 25px; font-size: 16px; color: #1e3a5f;">Result</h3>
      <pre id="result">Results will appear here...</pre>
    </div>

  </div>

  <div class="footer">
    Lab Program – Student Records System using MongoDB Query Operators
  </div>

  <script>
    async function addStudent() {
      const name = document.getElementById('name').value.trim();
      const age = document.getElementById('age').value;
      const department = document.getElementById('department').value.trim();
      const cgpa = document.getElementById('cgpa').value;

      if (!name || !age || !department || !cgpa) {
        alert('Please fill all the fields');
        return;
      }

      const data = {
        name: name,
        age: Number(age),
        department: department,
        cgpa: Number(cgpa)
      };

      try {
        const res = await fetch('http://localhost:5000/add', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(data)
        });

        const result = await res.json();
        alert(result.message || 'Student added successfully');

        document.getElementById('name').value = '';
        document.getElementById('age').value = '';
        document.getElementById('department').value = '';
        document.getElementById('cgpa').value = '';
      } catch (err) {
        alert('Error connecting to server. Make sure backend is running.');
      }
    }

    async function getData(url) {
      try {
        const res = await fetch(url);
        const data = await res.json();
        document.getElementById('result').innerText = JSON.stringify(data, null, 2);
      } catch (err) {
        document.getElementById('result').innerText = 'Error: Could not fetch data. Is the server running?';
      }
    }

    function getAll()  { getData('http://localhost:5000/all'); }
    function getEQ()   { getData('http://localhost:5000/eq/CSE'); }
    function getGT()   { getData('http://localhost:5000/gt/8'); }
    function getLT()   { getData('http://localhost:5000/lt/21'); }
    function getAND()  { getData('http://localhost:5000/and'); }
    function getOR()   { getData('http://localhost:5000/or'); }
  </script>

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

Make sure MongoDB is running, then in the project folder run:

Terminal
node server.js

Expected Output

When the server starts successfully, you will see:

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

In your browser, go to:

http://localhost:5000

From here you can add students using the form and test different MongoDB Query Operators by clicking the buttons. The results will appear in the Result box.

What Students Will Learn

  • Get All → find() → Retrieves all student documents
  • $eq → Exact match (Department = CSE)
  • $gt → Greater than (CGPA > 8)
  • $lt → Less than (Age < 21)
  • $and → Multiple conditions together (CSE and CGPA ≥ 8)
  • $or → Any one condition is enough (CSE or CGPA > 9)

Result: The Student Records System successfully demonstrates the use of important MongoDB Query Operators ($eq, $gt, $lt, $and, $or) for filtering and retrieving student data using Node.js, Express.js, and MongoDB.

Node.js Express.js MongoDB Mongoose Query Operators Database Lab

0 Ravula Kartheek:

Post a Comment