MongoDB is a NoSQL, document-based database widely used in modern web applications. This guide covers MongoDB from basic CRUD operations to advanced aggregation and real-world implementations.
1. insertOne / insertMany
Insert a single document:
db.students.insertOne({
name: "Amit",
age: 20,
course: "ADCA"
})
Insert multiple documents:
db.students.insertMany([
{ name: "Neha", age: 21 },
{ name: "Ravi", age: 22 }
])
2. find / findOne
Find all documents:
db.students.find()
Find with condition:
db.students.find({ course: "ADCA" })
Find one document:
db.students.findOne({ name: "Amit" })
Projection (show specific fields):
db.students.find({}, { name: 1, age: 1 })
3. updateOne / updateMany / $inc
Update One:
db.students.updateOne(
{ name: "Amit" },
{ $set: { age: 21 } }
)
Update Many:
db.students.updateMany(
{ course: "ADCA" },
{ $set: { duration: "6 Months" } }
)
4. deleteOne / deleteMany
db.students.deleteOne({ name: "Ravi" })
db.students.deleteMany({ course: "ADCA" })
Delete using _id (Primary key like MySQL):
db.users.deleteOne({
_id: ObjectId("64f1a9c8e4b0a12c9a123456")
})
5. Comparison Operators
$gt– Greater than$lt– Less than$gte– Greater than or equal to$lte– Less than or equal to
6. Logical Operators
$and– Match all conditions$or– Match any condition
7. sort / limit / skip
db.students.find().sort({ age: -1 })
db.students.find().limit(5)
db.students.find().skip(5).limit(5)
8. Indexes
Indexes improve query performance.
db.students.createIndex({ name: 1 })
9. Array Operators
MongoDB allows arrays inside documents.
- Add items
- Remove items
- Search inside arrays
$push – Add value to array
db.courses.updateOne(
{ _id: courseId },
{ $push: { students: studentId } }
)
$pull – Remove value from array
db.courses.updateOne(
{ _id: courseId },
{ $pull: { students: studentId } }
)
$addToSet – Add only if not exists
Use case: Avoid duplicate likes
db.videos.updateOne(
{ _id: videoId },
{ $addToSet: { likes: userId } }
)
10. Populate (Mongoose)
MongoDB does not support JOIN like SQL. Mongoose populate works like JOIN.
const teacherSchema = new Schema({
name: String,
experience: Number
})
const courseSchema = new Schema({
name: String,
teacher: {
type: mongoose.Schema.Types.ObjectId,
ref: "Teacher"
}
})
Course.find().populate("teacher")
Course.find().populate("teacher", "name")
Populate Multiple Documents
Course.find()
.populate("teacher")
.populate("category")
Course.find().populate([
{ path: "teacher" },
{ path: "category" }
])
Nested Populate (order → user → address)
Order.find().populate({
path: "user",
populate: {
path: "address"
}
})
11. Aggregation Basics
Aggregation uses a pipeline. Each stage takes input from the previous stage and outputs data for the next stage.
db.students.aggregate([
{ $group: { _id: "$course", totalStudents: { $sum: 1 } } }
])
This groups students by course and counts total students per course.
$project – Shape Output
db.students.aggregate([
{ $project: { name: 1, course: 1, _id: 0 } }
])
db.students.aggregate([
{
$project: {
fullName: { $concat: ["$firstName", " ", "$lastName"] },
course: 1,
_id: 0
}
}
])
$sort
db.students.aggregate([
{ $sort: { age: -1 } }
])
$limit
db.students.aggregate([
{ $limit: 5 }
])
$skip (Pagination)
db.students.aggregate([
{ $skip: 10 },
{ $limit: 5 }
])
$match
Works like WHERE clause in MySQL.
12. $lookup – Join Collections
db.products.aggregate([
{
$lookup: {
from: "categories",
localField: "categoryId",
foreignField: "_id",
as: "categoryDetails"
}
}
])
Advanced Lookup with Unwind & ReplaceRoot
db.products.aggregate([
{
$lookup:{
from:"categories",
localField:"category_id",
foreignField:"_id",
as:"categoryDetails"
}
},
{ $unwind:"$categoryDetails" },
{
$replaceRoot:{
newRoot:{
$mergeObjects:[
"$categoryDetails",
"$$ROOT"
]
}
}
},
{
$project:{
categoryDetails:0
}
}
])
Practice Queries
db.products.aggregate([
{
$lookup:{
from:"categories",
localField:"category_id",
foreignField:"_id",
as:"categoryDetails"
}
}
]).pretty()
db.products.aggregate([
{
$lookup:{
from:"categories",
localField:"category_id",
foreignField:"_id",
as:"categoryDetails"
}
},
{ $unwind:"$categoryDetails" }
]).pretty()
db.products.aggregate([
{
$lookup:{
from:"categories",
localField:"category_id",
foreignField:"_id",
as:"categoryDetails"
}
},
{ $unwind:"$categoryDetails" },
{
$replaceRoot:{
newRoot:{
$mergeObjects:[
"$categoryDetails",
"$$ROOT"
]
}
}
},
{
$project:{
name:1,
_id:1,
category:"$categoryDetails.name"
}
}
]).pretty()
13. Full Text Search
db.articles.createIndex({
title: "text",
content: "text"
})
db.articles.find(
{ $text: { $search: "MongoDB" } },
{ score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } })
14. Real-World Filter Implementation
const filters = {
category: "Shoes",
brand: ["Nike", "Adidas"],
price: { min: 1000, max: 5000 },
sizes: ["M", "L"]
}
let query = {}
if (filters.category) {
query.category = filters.category
}
if (filters.brand && filters.brand.length > 0) {
query.brand = { $in: filters.brand }
}
if (filters.price) {
query.price = {
$gte: filters.price.min,
$lte: filters.price.max
}
}
if (filters.sizes && filters.sizes.length > 0) {
query.sizes = { $in: filters.sizes }
}
console.log(query)
15. Pagination with Filters
const page = 2
const limit = 20
const products = await db.collection("products")
.find(query)
.skip((page - 1) * limit)
.limit(limit)
.toArray()