🚀 Cyber Security New Batch Start from 1 JunEnroll Now
Cyber Defence
Development

MongoDB Tutorial: Complete Database Guide for Web Developers in 2026

Learn MongoDB from scratch with this comprehensive tutorial for web developers. Covers database design, CRUD operations, aggregation, indexing, Mongoose ODM, and building scalable applications with MongoDB Atlas.

Amit Kumar
Amit KumarEthical Hacker & Founder
13 min read

MongoDB Tutorial: Complete Database Guide for Web Developers in 2026

MongoDB is the most popular NoSQL database for modern web applications, and a core component of the MERN and MEAN tech stacks. This comprehensive MongoDB tutorial covers everything web developers need to know about MongoDB in 2026, from basic operations to production-ready database design.

What Is MongoDB and Why Learn It

MongoDB is a document-oriented NoSQL database that stores data in flexible, JSON-like documents called BSON (Binary JSON). Unlike traditional relational databases that use tables and rows, MongoDB organizes data into collections of documents.

For web developers in India in 2026, MongoDB is essential because:

  • It pairs naturally with JavaScript and Node.js
  • Its flexible schema works well for evolving applications
  • Major companies (Netflix, Uber, eBay) use MongoDB at scale
  • It is a core component of the MERN stack

MongoDB vs Traditional SQL Databases

Before diving into this MongoDB tutorial, understanding when to use MongoDB versus SQL is important:

| Aspect | MongoDB | SQL (MySQL, PostgreSQL) |

|--------|---------|------------------------|

| Data Model | Document (JSON-like) | Tables and rows |

| Schema | Flexible, dynamic | Fixed structure |

| Relationships | Via referencing or embedding | Joins with foreign keys |

| Best For | Rapid prototyping, flexible data | Structured data, complex joins |

| Scalability | Horizontal (sharding) | Vertical and horizontal |

| Transactions | Limited (multi-document since v4) | Full ACID transactions |

When to Choose MongoDB

  • Building web or mobile applications with evolving requirements
  • Working with JSON-like data structures
  • Rapid prototyping and quick iterations
  • Applications with large numbers of reads
  • Microservices architectures

When to Choose SQL

  • Handling complex transactions (banking, inventory)
  • Applications with fixed, well-defined schemas
  • Reporting with complex joins and aggregations
  • Data integrity is critical

Installing and Setting Up MongoDB

Option 1: MongoDB Atlas (Cloud - Recommended)

MongoDB Atlas provides a free tier for learning:

  1. Go to mongodb.com/atlas
  2. Create a free account
  3. Create a free cluster (M0 sandbox)
  4. Create a database user
  5. Whitelist your IP address (or 0.0.0.0/0 for all IPs)
  6. Get your connection string

```javascript

// Connection string format

mongodb+srv://username:password@cluster.mongodb.net/database?retryWrites=true&w=majority

```

Option 2: Local MongoDB Installation

```bash

# macOS with Homebrew

brew install mongodb-community

brew services start mongodb-community

# Ubuntu/Debian

sudo apt update

sudo apt install -y mongodb-org

sudo systemctl start mongod

# Windows - Download from mongodb.com/try/download/community

```

MongoDB Basics: Database, Collection, Document

Understanding the Hierarchy

```

Database

└── Collection

└── Document

└── Field: Value

```

Basic Operations in MongoDB Shell

```javascript

// Switch to (or create) a database

use cyberdefence

// Create a collection implicitly

db.courses.insertOne({

title: "React JS Tutorial",

slug: "react-js-tutorial",

category: "Frontend",

price: 9999,

isPublished: true,

createdAt: new Date()

})

// View all databases

show dbs

// View collections in current database

show collections

// Drop a collection

db.courses.drop()

// Drop a database (must be in the database)

use cyberdefence

db.dropDatabase()

```

CRUD Operations: Create, Read, Update, Delete

This MongoDB tutorial covers all essential CRUD operations:

Insert Operations

```javascript

// Insert single document

db.courses.insertOne({

title: "Node.js Tutorial",

slug: "node-js-tutorial",

category: "Backend",

price: 12999,

duration: "8 weeks",

isPublished: true,

createdAt: new Date()

})

// Insert multiple documents

db.courses.insertMany([

{

title: "MongoDB Tutorial",

slug: "mongodb-tutorial",

category: "Database",

price: 9999,

isPublished: true

},

{

title: "Full Stack Development",

slug: "full-stack-course",

category: "Full Stack",

price: 49999,

isPublished: true

},

{

title: "Coming Soon Course",

slug: "future-course",

category: "Development",

price: 0,

isPublished: false

}

])

// Insert with ordered: false (continue on error)

db.courses.insertMany([...], { ordered: false })

```

Query Operations (Read)

```javascript

// Find all documents in collection

db.courses.find()

// Find all documents formatted

db.courses.find().pretty()

// Find documents matching criteria

db.courses.find({ category: "Frontend" })

db.courses.find({ price: { $gt: 5000 } })

db.courses.find({ isPublished: true })

// Find one document

db.courses.findOne({ slug: "react-js-tutorial" })

// Comparison operators

db.courses.find({ price: { $gt: 5000, $lt: 20000 } })

db.courses.find({ category: { $in: ["Frontend", "Backend"] } })

db.courses.find({ price: { $not: { $gt: 50000 } } })

// Logical operators

db.courses.find({

$and: [

{ isPublished: true },

{ price: { $lt: 50000 } }

]

})

// Combining OR and AND

db.courses.find({

$or: [

{ category: "Frontend" },

{ category: "Backend" }

],

price: { $lt: 20000 }

})

// Existence check

db.courses.find({ discount: { $exists: true } })

// Type check

db.courses.find({ price: { $type: "number" } })

// Regular expression

db.courses.find({ title: { $regex: /^React/, $options: "i" } })

```

Update Operations

```javascript

// Update single document

db.courses.updateOne(

{ slug: "react-js-tutorial" },

{

$set: {

price: 12999,

lastUpdated: new Date()

}

}

)

// Update multiple documents

db.courses.updateMany(

{ isPublished: false },

{

$set: {

isPublished: true,

publishedAt: new Date()

}

}

)

// Update with increment

db.courses.updateOne(

{ slug: "react-js-tutorial" },

{ $inc: { viewCount: 1 } }

)

// Update with array push

db.courses.updateOne(

{ slug: "react-js-tutorial" },

{

$push: {

tags: { $each: ["javascript", "react", "frontend"] }

}

}

)

// Update with array pull (remove)

db.courses.updateOne(

{ slug: "react-js-tutorial" },

{ $pull: { tags: "old-tag" } }

)

// Replace entire document (except _id)

db.courses.replaceOne(

{ slug: "react-js-tutorial" },

{

title: "Complete React JS Guide",

slug: "react-js-tutorial",

price: 14999

}

)

// Upsert (update or insert)

db.courses.updateOne(

{ slug: "new-course" },

{

$set: {

title: "New Course",

price: 9999,

createdAt: new Date()

}

},

{ upsert: true }

)

```

Delete Operations

```javascript

// Delete single document

db.courses.deleteOne({ slug: "unwanted-course" })

// Delete multiple documents

db.courses.deleteMany({ isPublished: false })

// Delete all documents in collection

db.courses.deleteMany({})

```

Projection: Selecting Fields

```javascript

// Include only specific fields

db.courses.find(

{ isPublished: true },

{ title: 1, slug: 1, price: 1 }

)

// Exclude specific fields

db.courses.find(

{ isPublished: true },

{ createdAt: 0 }

)

// Include _id explicitly

db.courses.find(

{},

{ title: 1, slug: 1, _id: 0 }

)

```

Sorting and Limiting Results

```javascript

// Sort ascending by price

db.courses.find().sort({ price: 1 })

// Sort descending by price

db.courses.find().sort({ price: -1 })

// Sort by multiple fields

db.courses.find().sort({ category: 1, price: -1 })

// Limit results

db.courses.find().limit(5)

// Skip results (pagination)

db.courses.find().skip(10).limit(10)

// Get most expensive published courses

db.courses.find(

{ isPublished: true },

{ title: 1, price: 1, category: 1 }

).sort({ price: -1 }).limit(3)

// Pagination helper

function getPage(collection, pageNumber, pageSize) {

return collection

.find({})

.skip((pageNumber - 1) * pageSize)

.limit(pageSize)

}

```

Aggregation Pipeline

Aggregation pipelines transform data in powerful ways:

```javascript

// Count courses by category

db.courses.aggregate([

{

$group: {

_id: "$category",

count: { $sum: 1 },

avgPrice: { $avg: "$price" }

}

}

])

// Filter and group

db.courses.aggregate([

{ $match: { isPublished: true } },

{

$group: {

_id: "$category",

count: { $sum: 1 },

totalRevenue: { $sum: "$price" },

avgPrice: { $avg: "$price" }

}

},

{ $sort: { count: -1 } }

])

// Using $lookup for joins

db.orders.aggregate([

{

$lookup: {

from: "customers",

localField: "customerId",

foreignField: "_id",

as: "customerDetails"

}

},

{ $unwind: "$customerDetails" },

{

$project: {

orderId: "$_id",

customerName: "$customerDetails.name",

total: 1

}

}

])

// Count with conditions

db.courses.aggregate([

{

$facet: {

published: [

{ $match: { isPublished: true } },

{ $count: "total" }

],

unpublished: [

{ $match: { isPublished: false } },

{ $count: "total" }

],

byCategory: [

{ $group: { _id: "$category", count: { $sum: 1 } } }

]

}

}

])

```

Indexing for Performance

Indexes dramatically improve query performance:

```javascript

// Create single field index

db.courses.createIndex({ slug: 1 }, { unique: true })

db.courses.createIndex({ category: 1 })

db.courses.createIndex({ isPublished: 1, price: -1 })

// Create compound index

db.courses.createIndex({ category: 1, price: -1 })

// Create text index for search

db.courses.createIndex({ title: "text", description: "text" })

// Search using text index

db.courses.find({

{ $text: { $search: "react tutorial" } }

})

// View query execution plan

db.courses.find({ category: "Frontend" }).explain("executionStats")

// List all indexes

db.courses.getIndexes()

// Drop an index

db.courses.dropIndex("category_1")

```

Mongoose: ODM for MongoDB with Node.js

Mongoose provides a schema-based model layer for MongoDB:

```bash

npm install mongoose

```

```javascript

// config/database.js

const mongoose = require('mongoose')

const connectDB = async () => {

try {

await mongoose.connect(process.env.MONGODB_URI)

console.log('MongoDB connected successfully')

} catch (error) {

console.error('MongoDB connection error:', error)

process.exit(1)

}

}

module.exports = connectDB

// models/Course.js

const mongoose = require('mongoose')

const courseSchema = new mongoose.Schema({

title: {

type: String,

required: [true, 'Course title is required'],

trim: true,

maxlength: [100, 'Title cannot exceed 100 characters']

},

slug: {

type: String,

required: [true, 'Course slug is required'],

unique: true,

lowercase: true,

index: true

},

description: {

type: String,

required: [true, 'Description is required'],

maxlength: [1000, 'Description cannot exceed 1000 characters']

},

category: {

type: String,

enum: {

values: ['Frontend', 'Backend', 'Database', 'DevOps', 'Full Stack'],

message: 'Invalid category'

},

required: true,

index: true

},

price: {

type: Number,

required: [true, 'Price is required'],

min: [0, 'Price cannot be negative']

},

isPublished: {

type: Boolean,

default: false,

index: true

},

tags: [{

type: String,

trim: true

}],

curriculum: [{

section: String,

lessons: [String]

}],

enrollmentCount: {

type: Number,

default: 0

},

ratings: {

average: { type: Number, default: 0 },

count: { type: Number, default: 0 }

},

createdAt: {

type: Date,

default: Date.now

},

updatedAt: {

type: Date,

default: Date.now

}

}, {

timestamps: true,

toJSON: { virtuals: true },

toObject: { virtuals: true }

})

// Text index for search

courseSchema.index({ title: 'text', description: 'text' })

// Pre-save middleware

courseSchema.pre('save', function(next) {

if (!this.slug && this.title) {

this.slug = this.title

.toLowerCase()

.replace(/[^a-z0-9]+/g, '-')

.replace(/(^-|-$)/g, '')

}

next()

})

// Static method for finding published courses

courseSchema.statics.findPublished = function() {

return this.find({ isPublished: true }).sort({ createdAt: -1 })

}

// Instance method

courseSchema.methods.getDiscountedPrice = function(discountPercent) {

return Math.round(this.price * (1 - discountPercent / 100))

}

const Course = mongoose.model('Course', courseSchema)

module.exports = Course

// Usage in Express route

const Course = require('./models/Course')

// Create

app.post('/api/courses', async (req, res) => {

try {

const course = await Course.create(req.body)

res.status(201).json({ success: true, data: course })

} catch (error) {

res.status(400).json({ success: false, error: error.message })

}

})

// Read all

app.get('/api/courses', async (req, res) => {

try {

const courses = await Course.findPublished()

res.json({ success: true, count: courses.length, data: courses })

} catch (error) {

res.status(500).json({ success: false, error: error.message })

}

})

// Read one

app.get('/api/courses/:slug', async (req, res) => {

try {

const course = await Course.findOne({ slug: req.params.slug })

if (!course) {

return res.status(404).json({ success: false, message: 'Course not found' })

}

res.json({ success: true, data: course })

} catch (error) {

res.status(500).json({ success: false, error: error.message })

}

})

// Update

app.put('/api/courses/:id', async (req, res) => {

try {

const course = await Course.findByIdAndUpdate(

req.params.id,

req.body,

{ new: true, runValidators: true }

)

if (!course) {

return res.status(404).json({ success: false, message: 'Course not found' })

}

res.json({ success: true, data: course })

} catch (error) {

res.status(400).json({ success: false, error: error.message })

}

})

// Delete

app.delete('/api/courses/:id', async (req, res) => {

try {

const course = await Course.findById(req.params.id)

if (!course) {

return res.status(404).json({ success: false, message: 'Course not found' })

}

await course.deleteOne()

res.json({ success: true, message: 'Course deleted successfully' })

} catch (error) {

res.status(500).json({ success: false, error: error.message })

}

})

```

MongoDB Atlas: Cloud Database Management

Setting Up MongoDB Atlas for Production

```bash

# Install MongoDB Compass (GUI for MongoDB)

# Download from mongodb.com/products/compass

# Or use mongosh (MongoDB Shell)

npm install -g mongosh

```

Connection in Node.js

```javascript

// .env file

MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/cyberdefence?retryWrites=true&w=majority

// Alternative with additional options

MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/cyberdefence?retryWrites=true&w=majority&maxPoolSize=10&minPoolSize=5

```

Environment-Specific Connections

```javascript

const mongoose = require('mongoose')

const connectDB = async () => {

try {

const conn = await mongoose.connect(process.env.MONGODB_URI, {

maxPoolSize: 10,

serverSelectionTimeoutMS: 5000,

socketTimeoutMS: 45000,

})

console.log(`MongoDB Atlas connected: ${conn.connection.host}`)

} catch (error) {

console.error(`MongoDB connection error: ${error.message}`)

process.exit(1)

}

}

module.exports = connectDB

```

Common MongoDB Patterns for Web Developers

Pagination

```javascript

async function getPaginatedCourses(page = 1, limit = 10) {

const skip = (page - 1) * limit

const courses = await Course.find({ isPublished: true })

.sort({ createdAt: -1 })

.skip(skip)

.limit(limit)

.select('title slug price category')

const total = await Course.countDocuments({ isPublished: true })

return {

courses,

pagination: {

currentPage: page,

totalPages: Math.ceil(total / limit),

totalCourses: total,

hasNextPage: page < Math.ceil(total / limit),

hasPrevPage: page > 1

}

}

}

```

Fuzzy Search

```javascript

async function searchCourses(query) {

// Simple text search

const results = await Course.find({

$text: { $search: query },

isPublished: true

}).select({ score: { $meta: "textScore" } })

.sort({ score: { $meta: "textScore" } })

// Regex search for partial matches

const regexResults = await Course.find({

title: { $regex: query, $options: 'i' },

isPublished: true

})

return { textResults: results, regexResults }

}

```

Updating Nested Arrays

```javascript

// Add lesson to section

await Course.updateOne(

{ slug: 'react-js-tutorial' },

{

$push: {

'curriculum.0.lessons': 'Advanced React Patterns'

}

}

)

// Remove lesson from section

await Course.updateOne(

{ slug: 'react-js-tutorial' },

{

$pull: {

'curriculum.0.lessons': 'Old Lesson'

}

}

)

```

Best Practices for MongoDB

  1. **Use meaningful field names** - userId, createdAt, isActive
  2. **Index frequently queried fields** - slug, category, published status
  3. **Use document validation** - prevent invalid data at write time
  4. **Implement soft deletes** - add deletedAt field instead of removing documents
  5. **Use projection** - only return fields you need
  6. **Handle connections properly** - singleton connection pattern in Node.js
  7. **Secure your database** - use environment variables for credentials

Next Steps After This MongoDB Tutorial

After completing this MongoDB tutorial:

  1. Build a complete CRUD API with Express and MongoDB
  2. Implement authentication with MongoDB user collections
  3. Practice aggregation pipelines with real data
  4. Learn MongoDB Atlas features for production deployment

For comprehensive database training as part of a web development course, the MERN stack program at Cyber Defence in Hisar, Haryana includes in-depth MongoDB training with Mongoose and production deployment.

FAQ: MongoDB Tutorial for Web Developers

How long does it take to learn MongoDB?

For web developers already familiar with JavaScript, learning MongoDB basics takes 1-2 weeks. Achieving proficiency with Mongoose, aggregation, and production patterns takes 1-2 months of practice.

Is MongoDB better than MySQL for web development?

MongoDB and MySQL serve different purposes. MongoDB is better for flexible data structures, rapid development, and JSON-centric applications. MySQL excels at complex relationships and transactional integrity. Most modern web applications use MongoDB as part of the MERN/PERN stack.

What is Mongoose in MongoDB?

Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides schema validation, type casting, middleware, and a higher-level API for working with MongoDB. Most Node.js applications use Mongoose rather than the native MongoDB driver.

Can I use MongoDB for free?

Yes, MongoDB Atlas offers a free tier (M0) with 512 MB storage, suitable for learning and small projects. You can also install MongoDB locally for free using the Community Server edition.

What is the salary of a MongoDB developer in India?

Developers with MongoDB skills command a premium in the job market. Entry-level: Rs 5-8 LPA. Mid-level: Rs 10-18 LPA. Senior: Rs 20-35 LPA. MongoDB is typically paired with Node.js, making full stack developers with MERN skills the most sought after.

Talk to a Cyber Defence Expert

Get a free consultation on cybersecurity, training and certifications. Our team responds within 10 minutes during business hours.