Introduction to MongoDB
MongoDB is a NoSQL document-oriented database that stores data in JSON-like BSON format.
MongoDB is highly scalable and widely used in modern web applications. Learning MongoDB helps in handling flexible data structures efficiently.
MongoDB Basics
Databases & Collections
-- Show all databases
show dbs;
-- Create / Switch Database
use School;
-- Show all collections
show collections;
-- Create Collection
db.createCollection("Students");
CRUD Operations
-- Insert Document
db.Students.insertOne({Name:"John", Age:15, Grade:"10th"});
-- Insert Multiple Documents
db.Students.insertMany([{Name:"Jane", Age:16},{Name:"Mike", Age:17}]);
-- Find Documents
db.Students.find();
db.Students.find({Age:16});
-- Update Document
db.Students.updateOne({Name:"John"}, {$set:{Age:16}});
-- Delete Document
db.Students.deleteOne({Name:"John"});
MongoDB Queries
Filtering Documents
db.Students.find({Age: {$gt:15}});
db.Students.find({Grade:"10th"});
Sorting
db.Students.find().sort({Age:1}); // Ascending
db.Students.find().sort({Age:-1}); // Descending
Aggregations
db.Students.aggregate([
{$match: {Age: {$gt:15}}},
{$group: {_id:"$Grade", avgAge: {$avg:"$Age"}}}
]);
Indexes & Performance
-- Create Index
db.Students.createIndex({Name:1});
-- View Indexes
db.Students.getIndexes();
Explain Query
db.Students.find({Age:16}).explain();
Advanced MongoDB
Aggregation Pipeline
db.Orders.aggregate([
{$match: {status:"Shipped"}},
{$group: {_id:"$customerId", total: {$sum:"$amount"}}},
{$sort: {total:-1}}
]);
Embedded Documents & Arrays
db.Students.insertOne({
Name:"Alice",
Courses:[{Name:"Math", Score:90},{Name:"Science", Score:85}]
});
db.Students.find({"Courses.Name":"Math"});
Transactions
const session = db.getMongo().startSession();
session.startTransaction();
db.Students.updateOne({Name:"John"}, {$set:{Age:17}}, {session});
session.commitTransaction();
session.endSession();
Views
db.createView("TeenStudents", "Students", [{$match:{Age:{$gte:13,$lte:19}}}]);
db.TeenStudents.find();