1 of 32

PRACTICAL DATABASE TECHNOLOGY

MongoDB

From Installation to Working Commands

A hands-on guide to setup, databases, collections, CRUD, queries, aggregation, indexes, and Node.js integration.

TEACHING PRESENTATION • WITH EXECUTABLE EXAMPLES

{ }

JSON

BSON

2 of 32

01 • GETTING STARTED

Learning outcomes

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

2

Explain MongoDB, document databases, BSON, collections, and documents.

Install MongoDB Community Server, MongoDB Shell (mongosh), and Compass.

Connect to a local server and execute essential shell commands.

Perform insert, read, update, and delete operations.

Filter, project, sort, limit, aggregate, and count documents.

Connect an Express.js application to MongoDB using Mongoose.

Learning approach

One running example is used throughout: a CollegeDB database with a students collection.

Before you begin

Use a local development machine and avoid using real student personal data in demos.

3 of 32

01 • GETTING STARTED

Roadmap: from setup to application

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

3

01

Install

Server • Shell • Compass

02

Connect

mongosh • localhost

03

Create

Database • Collection

04

Manage

CRUD • Queries

05

Analyze

Aggregation • Indexes

06

Integrate

Node.js • Express • Mongoose

4 of 32

02 • CORE CONCEPTS

What is MongoDB?

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

4

MongoDB is a document-oriented NoSQL database.

Records are stored as BSON documents, similar in shape to JSON.

Documents are grouped into collections; collections belong to databases.

A document can contain nested objects and arrays.

Flexible document structure supports evolving application requirements.

EXAMPLE BSON-STYLE DOCUMENT (JSON SYNTAX)

{

"rollNo": "101",

"name": "Ravi",

"branch": "AI&DS",

"marks": 85,

"skills": ["Python", "SQL"],

"address": {

"city": "Vijayawada"

}

}

Remember

MongoDB stores documents in BSON internally; the example is shown in readable JSON syntax.

5 of 32

02 • CORE CONCEPTS

Database, collection, document, field

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

5

Database

CollegeDB

A container for collections

Collection

students

A group of related documents

Document

One student record

A single BSON record

Field

rollNo, name, marks

A key-value pair

A DOCUMENT INCLUDES A UNIQUE _ID

{

"_id": ObjectId("..."),

"rollNo": "101",

"name": "Ravi"

}

6 of 32

02 • CORE CONCEPTS

Relational databases vs MongoDB

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

6

Relational database

MongoDB

Database / schema

Database

Table

Collection

Row

Document

Column

Field

JOIN / relations

References or embedded documents

Fixed table structure

Flexible document structure

Design tip

Choose a data model based on application access patterns—not just on whether a database is SQL or NoSQL.

7 of 32

03 • INSTALLATION

Installation overview (Windows)

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

7

1. Download MongoDB Community Server for Windows from the official website.

2. Run the MSI installer and follow the setup wizard.

3. Choose the Complete setup unless your environment requires a custom setup.

4. Install MongoDB as a Windows Service for convenient startup.

5. Install MongoDB Shell (mongosh) separately if it is not included.

6. Optionally install MongoDB Compass for graphical exploration.

Official downloads

Community Server: mongodb.com/try/download/community

Shell: mongodb.com/try/download/shell

Installation paths

Keep the data directory and log directory configured by the installer unless you have a reason to change them.

Official guide: https://www.mongodb.com/docs/manual/installation/

8 of 32

03 • INSTALLATION

Verify the installation

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

8

Open Command Prompt or PowerShell

CHECK MONGODB SHELL

mongosh --version

CONNECT TO LOCAL MONGODB

mongosh

If a version number appears, the shell is installed.

If 'mongosh' is not recognized, check installation and PATH.

A successful local connection usually targets mongodb://127.0.0.1:27017.

Common issue

The shell and database server are separate components. Installing mongosh alone does not install or start the server.

9 of 32

03 • INSTALLATION

Start and stop the MongoDB service

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

9

Windows (run as Administrator when required)

START / STOP SERVICE

net start MongoDB

​

net stop MongoDB

Check service status

POWERSHELL

Get-Service MongoDB

If the service name differs

Open Services (services.msc) and check the installed service name. If you did not install MongoDB as a service, start mongod with the configuration appropriate for your installation.

10 of 32

04 • SHELL COMMANDS

Connect with MongoDB Shell (mongosh)

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

10

DEFAULT LOCAL CONNECTION

mongosh

EXPLICIT CONNECTION STRING

mongosh "mongodb://127.0.0.1:27017"

mongosh is an interactive JavaScript-based shell.

Commands are executed against the connected MongoDB deployment.

Local default port is commonly 27017.

Use the connection string supplied by your administrator for remote or authenticated databases.

Connection check

If the shell connects successfully, run show dbs to list databases visible to your account.

11 of 32

04 • SHELL COMMANDS

Essential navigation commands

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

11

RUN IN MONGOSH

show dbs

use CollegeDB

db

show collections

db.help()

show dbs — list databases available to the user.

use CollegeDB — switch to a database; it is created on first data write.

db — display the current database.

show collections — list collections in the current database.

db.help() — show database-level helper commands.

Important

A database may not appear in show dbs until it contains data.

12 of 32

05 • CRUD OPERATIONS

Create a collection and insert documents

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

12

CREATE COLLECTION + INSERT ONE

use CollegeDB

​

db.createCollection("students")

​

db.students.insertOne({

rollNo: "101",

name: "Ravi",

branch: "AI&DS",

marks: 85

})

insertOne() adds one document.

MongoDB creates _id automatically if omitted.

The result reports acknowledged status and insertedId.

Output concept

acknowledged: true

insertedId: ObjectId("…")

13 of 32

05 • CRUD OPERATIONS

Insert multiple documents with insertMany()

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

13

INSERT ARRAY OF DOCUMENTS

db.students.insertMany([

{ rollNo: "102", name: "Sita", branch: "CSE", marks: 92 },

{ rollNo: "103", name: "Kiran", branch: "AI&DS", marks: 76 },

{ rollNo: "104", name: "Meena", branch: "ECE", marks: 88 }

])

Pass an array of document objects.

Each object becomes a separate document.

Use double quotes around string values for standard JSON-style consistency.

Avoid duplicate values for fields that you intend to make unique.

14 of 32

05 • CRUD OPERATIONS

Read documents: find() and findOne()

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

14

READ OPERATIONS

db.students.find()

​

db.students.findOne()

​

db.students.find({ branch: "AI&DS" })

Example output shape

ONE MATCHING DOCUMENT

{

"_id": ObjectId("..."),

"rollNo": "101",

"name": "Ravi",

"branch": "AI&DS",

"marks": 85

}

Tip

find() returns a cursor of matching documents; findOne() returns one matching document or null.

15 of 32

06 • QUERYING

Filter documents with query operators

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

15

COMPARISON OPERATORS

// Marks greater than 80

db.students.find({ marks: { $gt: 80 } })

​

// Marks from 75 to 90 inclusive

db.students.find({ marks: { $gte: 75, $lte: 90 } })

​

// Branch is AI&DS or CSE

db.students.find({ branch: { $in: ["AI&DS", "CSE"] } })

$gt / $gte — greater than / greater than or equal.

$lt / $lte — less than / less than or equal.

$eq / $ne — equal / not equal.

$in / $nin — value in / not in an array.

Use the field name as the query key.

16 of 32

06 • QUERYING

Combine conditions with logical operators

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

16

AND / OR EXAMPLES

// AND is implicit when fields are combined

db.students.find({ branch: "AI&DS", marks: { $gte: 80 } })

​

// OR condition

db.students.find({

$or: [

{ branch: "CSE" },

{ marks: { $gte: 90 } }

]

})

Multiple field conditions in one object are combined with AND.

$or matches at least one condition.

$and can express explicit conjunctions.

$not and $nor are available for other logic patterns.

17 of 32

06 • QUERYING

Projection, sorting, and limiting

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

17

SHAPE AND ORDER RESULTS

// Show only name and marks; hide _id

db.students.find({}, { name: 1, marks: 1, _id: 0 })

​

// Highest marks first

db.students.find().sort({ marks: -1 })

​

// Show top 2

db.students.find().sort({ marks: -1 }).limit(2)

Projection controls which fields appear.

1 includes a field; 0 excludes a field.

The _id field is included by default unless excluded.

sort({ marks: 1 }) is ascending; -1 is descending.

limit(n) caps the number of returned documents.

18 of 32

05 • CRUD OPERATIONS

Update documents: updateOne() and updateMany()

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

18

UPDATE OPERATIONS

// Update one matching document

db.students.updateOne(

{ rollNo: "101" },

{ $set: { marks: 90 } }

)

​

// Add 5 marks to every AI&DS student

db.students.updateMany(

{ branch: "AI&DS" },

{ $inc: { marks: 5 } }

)

$set — sets a field to a specified value.

$inc — increments or decrements a numeric field.

updateOne() changes at most one matching document.

updateMany() changes every matching document.

Check matchedCount and modifiedCount in the result.

19 of 32

05 • CRUD OPERATIONS

Delete documents safely

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

19

DELETE OPERATIONS

// Delete one matching student

db.students.deleteOne({ rollNo: "104" })

​

// Delete all students in a branch

db.students.deleteMany({ branch: "ECE" })

Safety rule

Run the matching find() query first to verify which documents will be deleted.

Avoid accidental deletion

deleteMany({}) matches every document in the collection. Use it only when you deliberately intend to clear all records.

20 of 32

06 • QUERYING

Count, distinct, and check fields

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

20

USEFUL QUERY HELPERS

db.students.countDocuments()

​

db.students.countDocuments({ branch: "AI&DS" })

​

db.students.distinct("branch")

​

db.students.find({ marks: { $exists: true } })

countDocuments() counts all or matching documents.

distinct() returns unique values for a field.

$exists checks whether a field is present.

These commands are useful for quick data-quality checks.

21 of 32

07 • ANALYSIS

Aggregation pipeline: summarize data

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

21

GROUP STUDENTS BY BRANCH

db.students.aggregate([

{ $group: {

_id: "$branch",

averageMarks: { $avg: "$marks" },

studentCount: { $sum: 1 }

}},

{ $sort: { averageMarks: -1 } }

])

$match — filter documents.

$group — calculate grouped values.

$project — reshape fields.

$sort — order pipeline results.

$limit — retain a maximum number of results.

Think of a pipeline

Documents flow through ordered stages; each stage transforms or filters the data.

22 of 32

07 • ANALYSIS

Indexes: improve query performance

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

22

INDEX COMMANDS

// Create an index on rollNo

db.students.createIndex({ rollNo: 1 })

​

// List indexes

db.students.getIndexes()

​

// Remove a named index

db.students.dropIndex("rollNo_1")

Indexes can reduce the amount of data MongoDB scans.

They add storage overhead and can slow writes.

Create indexes for fields used frequently in filters and sorting.

Use explain() to inspect query execution plans.

23 of 32

07 • ANALYSIS

Data types, _id, and schema validation

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

23

Every standard MongoDB document has a unique _id field.

Common BSON types include string, number, boolean, date, array, object, and ObjectId.

Documents in a collection can have different fields.

Flexible schema does not mean data quality is unimportant.

Validation rules can enforce required fields and data types.

EXAMPLE VALUES AND TYPES

{

rollNo: "101",

name: "Ravi",

active: true,

enrolledOn: ISODate("2026-08-01"),

subjects: ["DBMS", "NLP"]

}

24 of 32

08 • GUI AND TROUBLESHOOTING

MongoDB Compass: visual workflow

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

24

Open Compass and connect to mongodb://127.0.0.1:27017.

Select a database and open a collection.

Use the Documents tab to browse and edit records.

Use the Filter field for queries such as { marks: { $gt: 80 } }.

Use Aggregations to build pipeline stages visually.

Use Indexes to inspect indexes on a collection.

Connect

Local URI

→

Database

CollegeDB

→

Collection

students

→

Documents

Browse / filter

Compass is optional

You can complete all shell exercises with mongosh; Compass is a visual alternative.

25 of 32

08 • GUI AND TROUBLESHOOTING

Common errors and how to resolve them

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

25

mongosh not recognized

Install MongoDB Shell and add its install folder to PATH; reopen the terminal.

Connection refused

Confirm MongoDB Server is installed and running; check host and port.

Authentication failed

Verify username, password, authentication database, and assigned roles.

Database not shown

Write data first; empty databases may not appear in show dbs.

Duplicate key error

Check the unique index and ensure the key value is not already present.

26 of 32

09 • APPLICATION INTEGRATION

How an Express app uses MongoDB

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

26

Client

Browser / Postman

→

Express API

Routes + middleware

→

Mongoose

Schema + model

→

MongoDB

Database + collection

Express defines HTTP endpoints such as GET /students and POST /students.

Mongoose maps application objects to MongoDB documents and provides schema/model helpers.

The MongoDB server stores and retrieves the data; the client should not connect directly to the database.

27 of 32

09 • APPLICATION INTEGRATION

Express + Mongoose: minimal connection example

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

27

APP.JS — TEACHING EXAMPLE

const express = require("express");

const mongoose = require("mongoose");

const app = express();

app.use(express.json());

​

mongoose.connect("mongodb://127.0.0.1:27017/CollegeDB")

.then(() => console.log("MongoDB connected"))

.catch(err => console.error(err));

​

const Student = mongoose.model("Student", new mongoose.Schema({

rollNo: String, name: String, branch: String, marks: Number

}));

​

app.get("/students", async (req, res) => {

res.json(await Student.find());

});

​

app.listen(3000, () => console.log("Server on 3000"));

Install dependencies: npm install express mongoose

Start MongoDB Server before running the app.

Run: node app.js

Test: GET http://localhost:3000/students

Production apps should add error handling, environment variables, and validation.

28 of 32

09 • APPLICATION INTEGRATION

Typical REST endpoints for student CRUD

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

28

POST

/students

Create a student

GET

/students

List all students

GET

/students/:id

Read one student

PUT / PATCH

/students/:id

Update a student

DELETE

/students/:id

Delete a student

API testing

Use Postman or curl to send JSON requests; ensure the server uses app.use(express.json()).

29 of 32

10 • PRACTICE

Guided lab: build and verify CollegeDB

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

29

1. Connect to MongoDB using mongosh.

2. Create CollegeDB and insert at least five student documents.

3. Retrieve all students and only AI&DS students.

4. Find students with marks greater than or equal to 80.

5. Display name and marks only; sort by marks descending.

6. Update one student and verify the change.

7. Delete one test record and count remaining records.

8. Group students by branch and calculate average marks.

Expected deliverable

A working database with a students collection and verified results for every command.

Assessment idea

Ask students to explain the purpose of each command and predict its output before execution.

30 of 32

10 • PRACTICE

Quick command reference

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

30

SETUP + CREATE + READ

show dbs

use CollegeDB

show collections

db.createCollection("students")

db.students.insertOne({...})

db.students.insertMany([...])

db.students.find()

db.students.findOne({...})

UPDATE + DELETE + ANALYZE

db.students.updateOne(filter, update)

db.students.updateMany(filter, update)

db.students.deleteOne(filter)

db.students.deleteMany(filter)

db.students.countDocuments()

db.students.distinct("branch")

db.students.createIndex({ rollNo: 1 })

db.students.aggregate([...])

Replace {...}, [...], filter, and update with valid document objects and operators before running.

31 of 32

10 • PRACTICE

Key takeaways

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

31

MongoDB organizes data as databases → collections → documents.

mongosh is the command-line environment; Compass provides a GUI.

CRUD means Create, Read, Update, and Delete.

Query operators filter data; projection, sorting, and limit shape results.

Aggregation summarizes data; indexes can speed up common queries.

Express + Mongoose connects database operations to HTTP APIs.

Next step

Practice every command on sample data and inspect the returned result.

Safety reminder

Do not run destructive commands on production data without review and backup.

32 of 32

10 • PRACTICE

Free learning resources and references

MONGODB • INSTALLATION TO PRACTICAL COMMANDS

32

MongoDB Manual

https://www.mongodb.com/docs/manual/

Installation guide

https://www.mongodb.com/docs/manual/installation/

MongoDB Shell (mongosh)

https://www.mongodb.com/docs/mongodb-shell/

MongoDB University

https://learn.mongodb.com/

MongoDB Compass

https://www.mongodb.com/docs/compass/

W3Schools MongoDB tutorial

https://www.w3schools.com/mongodb/

Mongoose documentation

https://mongoosejs.com/docs/

Reuse note

Use these links as references; check each site's terms before reproducing images or substantial text.