MongoDB Learning Document
1. Introduction to MongoDB
MongoDB is a popular NoSQL, document-oriented database.
It stores data in flexible, JSON-like documents, making it easy to work with
dynamic or unstructured data.
Key Features:
Schema-less (no fixed columns)
Stores data as documents (BSON format)
Supports powerful queries and aggregations
Scalable and high performance
2. Setting Up MongoDB
Install MongoDB: Official Installation Guide
Start the MongoDB server:
On Windows: Run mongod in Command Prompt
On Linux/Mac: Run mongod in Terminal
Connect to MongoDB shell:
Run mongo in your terminal
3. Basic Database Operations
Command Description Example
show dbs List all databases show dbs
Command Description Example
use <dbname> Switch/create database use mydb
db Show current database db
db.dropDatabase() Delete current database db.dropDatabase()
4. Working with Collections
Command Description Example
List all
show collections show collections
collections
Create a
db.createCollection('name') db.createCollection('us
collection
Delete a
db.<collection>.drop() collection db.users.drop()
5. CRUD Operations
A. Insert Documents
Insert one document:
db.users.insertOne({name: "Alice", age: 25})
Insert multiple documents:
db.users.insertMany([{name: "Bob"}, {name: "Carol"}])
B. Read Documents
Find all documents:
db.users.find()
Find with query:
db.users.find({age: 25})
Find one document:
db.users.findOne({name: "Alice"})
C. Update Documents
Update one document:
db.users.updateOne({name: "Alice"}, {$set: {age: 26}})
Update many documents:
db.users.updateMany({age: 25}, {$set: {active: true}})
D. Delete Documents
Delete one document:
db.users.deleteOne({name: "Alice"})
Delete many documents:
db.users.deleteMany({age: 25})
6. Query Modifiers
Sort results:
db.users.find().sort({age: -1})
Limit results:
db.users.find().limit(5)
Skip results:
db.users.find().skip(10)
7. Aggregation
Group and sum example:
db.sales.aggregate([
{ $group: { _id: "$item", total: { $sum: "$amount" } } }
])
8. Indexing
Create an index:
db.users.createIndex({name: 1})
List indexes:
db.users.getIndexes()
Drop an index:
db.users.dropIndex("name_1")
9. User and Role Management
Create a user:
db.createUser({
user: "admin",
pwd: "password",
roles: ["readWrite"]
})
List users:
db.getUsers()
Delete a user:
db.dropUser("admin")
10. Admin and Monitoring Commands
Database stats:
db.stats()
Server status:
db.serverStatus()
Current operations:
db.currentOp()
11. Practice Exercises
1. Create a database and a collection.
2. Insert several documents into the collection.
3. Query documents with different filters.
4. Update and delete specific documents.
5. Create an index and observe query performance.
6. Aggregate data using the aggregation framework.