MongoDB All Commands & Examples for Practice and Learning
(Complete Hands-On Guide – Copy, Paste, Run in mongosh)
MongoDB All Commands & Examples for Practice and Learning
MongoDB All Commands & Examples for Practice and Learning
MongoDB All Commands & Examples for Practice and Learning
(Complete Hands-On Guide – Copy, Paste, Run in mongosh)
Setup: Start MongoDB & Connect
# Start server (if not running)
mongod
# Open shell
mongosh
// Switch to practice database
use practiceDB
1. DATABASE COMMANDS
| Command | Example |
|---|---|
| Create / Switch DB | use practiceDB |
| Show all DBs | show dbs |
| Current DB | db |
| Drop DB | db.dropDatabase() |
// Practice
use practiceDB
db.dropDatabase() // Clean start
show dbs
2. COLLECTION COMMANDS
// Create collection (implicit)
db.createCollection("users")
// List collections
show collections
// Drop collection
db.users.drop()
3. INSERT COMMANDS (CREATE)
Insert One
db.users.insertOne({
name: "Alice",
age: 25,
city: "New York",
hobbies: ["reading", "cycling"],
active: true,
joined: new Date()
})
Insert Many
db.users.insertMany([
{ name: "Bob", age: 30, city: "London", hobbies: ["gaming"], active: false },
{ name: "Charlie", age: 35, city: "Paris", hobbies: ["cooking", "tennis"], active: true },
{ name: "Diana", age: 28, city: "Tokyo", hobbies: ["painting"], active: true }
])
4. QUERY COMMANDS (READ)
Find All
db.users.find().pretty()
Find with Condition
db.users.find({ age: { $gt: 28 } }).pretty()
db.users.find({ city: "Paris" }).pretty()
Find One
db.users.findOne({ name: "Alice" })
Projection (Select fields)
db.users.find({}, { name: 1, city: 1, _id: 0 }).pretty()
Logical Operators
// AND
db.users.find({ age: { $gt: 25 }, active: true })
// OR
db.users.find({ $or: [{ city: "Tokyo" }, { age: 35 }] })
// NOT
db.users.find({ age: { $ne: 30 } })
Array Queries
// Has hobby "gaming"
db.users.find({ hobbies: "gaming" })
// Has multiple hobbies
db.users.find({ hobbies: { $all: ["cooking", "tennis"] } })
// Array size
db.users.find({ hobbies: { $size: 2 } })
// Element match
db.users.find({ "hobbies.0": "reading" }) // First hobby
Regex
db.users.find({ name: /^A/ }) // Starts with A
db.users.find({ name: /bob/i }) // Case-insensitive
5. UPDATE COMMANDS
Update One
db.users.updateOne(
{ name: "Alice" },
{ $set: { age: 26, city: "Boston" } }
)
Update Many
db.users.updateMany(
{ active: false },
{ $set: { active: true } }
)
Increment / Decrement
db.users.updateOne(
{ name: "Bob" },
{ $inc: { age: 1 } }
)
Push to Array
db.users.updateOne(
{ name: "Charlie" },
{ $push: { hobbies: "swimming" } }
)
Pull from Array
db.users.updateOne(
{ name: "Diana" },
{ $pull: { hobbies: "painting" } }
)
Replace Document
db.users.replaceOne(
{ name: "Bob" },
{ name: "Bobby", age: 31, city: "Berlin", active: true }
)
Upsert (Insert if not exists)
db.users.updateOne(
{ name: "Eve" },
{ $set: { age: 29, city: "Sydney" } },
{ upsert: true }
)
6. DELETE COMMANDS
Delete One
db.users.deleteOne({ name: "Eve" })
Delete Many
db.users.deleteMany({ active: false })
Drop Collection / DB
db.users.drop()
db.dropDatabase()
7. INDEX COMMANDS
// Single field
db.users.createIndex({ age: 1 })
// Compound
db.users.createIndex({ city: 1, age: -1 })
// Unique
db.users.createIndex({ email: 1 }, { unique: true })
// Text index
db.articles.createIndex({ title: "text", content: "text" })
// Partial index
db.users.createIndex(
{ age: 1 },
{ partialFilterExpression: { active: true } }
)
// Sparse
db.users.createIndex({ phone: 1 }, { sparse: true })
// TTL (auto-delete after 1 hour)
db.sessions.createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 3600 }
)
// List indexes
db.users.getIndexes()
// Drop index
db.users.dropIndex("age_1")
8. AGGREGATION PIPELINE EXAMPLES
Basic: Filter + Project
db.users.aggregate([
{ $match: { age: { $gte: 30 } } },
{ $project: { name: 1, age: 1, _id: 0 } }
])
Group & Count
db.users.aggregate([
{ $group: { _id: "$city", count: { $sum: 1 } } }
])
Average Age per City
db.users.aggregate([
{ $group: {
_id: "$city",
avgAge: { $avg: "$age" },
totalUsers: { $sum: 1 }
}}
])
Top 2 Cities by User Count
db.users.aggregate([
{ $group: { _id: "$city", count: { $sum: 1 } } },
{ $sort: { count: -1 } },
{ $limit: 2 }
])
Unwind Array
db.users.aggregate([
{ $unwind: "$hobbies" },
{ $group: { _id: "$hobbies", count: { $sum: 1 } } },
{ $sort: { count: -1 } }
])
Lookup (Join)
// Assume orders collection
db.users.aggregate([
{
$lookup: {
from: "orders",
localField: "name",
foreignField: "customer",
as: "orders"
}
},
{ $project: { name: 1, orderCount: { $size: "$orders" } } }
])
Add Computed Field
db.users.aggregate([
{
$addFields: {
isAdult: { $gte: ["$age", 18] },
hobbyCount: { $size: "$hobbies" }
}
}
])
Write Output to New Collection
db.users.aggregate([
{ $match: { active: true } },
{ $out: "active_users" }
])
9. SAMPLE DATA FOR PRACTICE
// Insert sample data
db.products.insertMany([
{ name: "Laptop", price: 1200, category: "Electronics", inStock: true, tags: ["portable", "work"] },
{ name: "Mouse", price: 25, category: "Electronics", inStock: true, tags: ["wireless"] },
{ name: "Book", price: 15, category: "Education", inStock: false, tags: ["paperback"] },
{ name: "Pen", price: 2, category: "Stationery", inStock: true, tags: ["blue", "ballpoint"] }
])
db.orders.insertMany([
{ orderId: "O1", customer: "Alice", items: ["Laptop", "Mouse"], total: 1225, status: "shipped" },
{ orderId: "O2", customer: "Bob", items: ["Book"], total: 15, status: "pending" }
])
10. PRACTICE EXERCISES (Try These!)
-
Find all users older than 28 from Tokyo
js db.users.find({ age: { $gt: 28 }, city: "Tokyo" }) -
Update all inactive users to active
js db.users.updateMany({ active: false }, { $set: { active: true } }) -
Count products in "Electronics" category
js db.products.countDocuments({ category: "Electronics" }) -
Get total sales per customer
js db.orders.aggregate([ { $group: { _id: "$customer", totalSpent: { $sum: "$total" } } } ]) -
Find products with "wireless" tag
js db.products.find({ tags: "wireless" }) -
Add index on
priceand sort descending
js db.products.createIndex({ price: -1 }) db.products.find().sort({ price: -1 }) -
Create TTL index on
createdAt
js db.logs.createIndex({ createdAt: 1 }, { expireAfterSeconds: 86400 })
11. USEFUL SYSTEM COMMANDS
// Server status
db.serverStatus()
// Current operations
db.currentOp()
// Kill long-running op
db.killOp(<opId>)
// Collection stats
db.users.stats()
// Validate collection
db.users.validate()
// Compact (defragment)
db.runCommand({ compact: "users" })
12. MONGOSH TIPS
// Pretty print
.pretty()
// Limit results
.limit(5)
// Count
.count()
// Explain query plan
db.users.find({ age: 30 }).explain("executionStats")
// Clear screen
cls
// Exit
exit
Download This Guide as .js File
// Save as: mongodb-practice.js
// Run: mongosh mongodb-practice.js
use practiceDB
db.dropDatabase()
print("=== INSERTING DATA ===")
db.users.insertMany([...]) // paste all insert commands
print("=== PRACTICE QUERIES ===")
// paste all queries
Resources
You now have 100+ working MongoDB commands!
Copy → Paste → Run → Learn
Next Step: Build a mini project (e.g., Todo App, Blog, Inventory) using these commands.
Want a full project template or Node.js + MongoDB example? Just ask!
MongoDB All Commands & Examples for Practice and Learning
(Complete Hands-On Guide – Copy, Paste, Run in mongosh)
MongoDB All Commands & Examples for Practice and Learning
MongoDB All Commands & Examples for Practice and Learning
MongoDB All Commands & Examples for Practice and Learning
(Complete Hands-On Guide – Copy, Paste, Run in mongosh)
Setup: Start MongoDB & Connect
# Start server (if not running)
mongod
# Open shell
mongosh
// Switch to practice database
use practiceDB
1. DATABASE COMMANDS
| Command | Example |
|---|---|
| Create / Switch DB | use practiceDB |
| Show all DBs | show dbs |
| Current DB | db |
| Drop DB | db.dropDatabase() |
// Practice
use practiceDB
db.dropDatabase() // Clean start
show dbs
2. COLLECTION COMMANDS
// Create collection (implicit)
db.createCollection("users")
// List collections
show collections
// Drop collection
db.users.drop()
3. INSERT COMMANDS (CREATE)
Insert One
db.users.insertOne({
name: "Alice",
age: 25,
city: "New York",
hobbies: ["reading", "cycling"],
active: true,
joined: new Date()
})
Insert Many
db.users.insertMany([
{ name: "Bob", age: 30, city: "London", hobbies: ["gaming"], active: false },
{ name: "Charlie", age: 35, city: "Paris", hobbies: ["cooking", "tennis"], active: true },
{ name: "Diana", age: 28, city: "Tokyo", hobbies: ["painting"], active: true }
])
4. QUERY COMMANDS (READ)
Find All
db.users.find().pretty()
Find with Condition
db.users.find({ age: { $gt: 28 } }).pretty()
db.users.find({ city: "Paris" }).pretty()
Find One
db.users.findOne({ name: "Alice" })
Projection (Select fields)
db.users.find({}, { name: 1, city: 1, _id: 0 }).pretty()
Logical Operators
// AND
db.users.find({ age: { $gt: 25 }, active: true })
// OR
db.users.find({ $or: [{ city: "Tokyo" }, { age: 35 }] })
// NOT
db.users.find({ age: { $ne: 30 } })
Array Queries
// Has hobby "gaming"
db.users.find({ hobbies: "gaming" })
// Has multiple hobbies
db.users.find({ hobbies: { $all: ["cooking", "tennis"] } })
// Array size
db.users.find({ hobbies: { $size: 2 } })
// Element match
db.users.find({ "hobbies.0": "reading" }) // First hobby
Regex
db.users.find({ name: /^A/ }) // Starts with A
db.users.find({ name: /bob/i }) // Case-insensitive
5. UPDATE COMMANDS
Update One
db.users.updateOne(
{ name: "Alice" },
{ $set: { age: 26, city: "Boston" } }
)
Update Many
db.users.updateMany(
{ active: false },
{ $set: { active: true } }
)
Increment / Decrement
db.users.updateOne(
{ name: "Bob" },
{ $inc: { age: 1 } }
)
Push to Array
db.users.updateOne(
{ name: "Charlie" },
{ $push: { hobbies: "swimming" } }
)
Pull from Array
db.users.updateOne(
{ name: "Diana" },
{ $pull: { hobbies: "painting" } }
)
Replace Document
db.users.replaceOne(
{ name: "Bob" },
{ name: "Bobby", age: 31, city: "Berlin", active: true }
)
Upsert (Insert if not exists)
db.users.updateOne(
{ name: "Eve" },
{ $set: { age: 29, city: "Sydney" } },
{ upsert: true }
)
6. DELETE COMMANDS
Delete One
db.users.deleteOne({ name: "Eve" })
Delete Many
db.users.deleteMany({ active: false })
Drop Collection / DB
db.users.drop()
db.dropDatabase()
7. INDEX COMMANDS
// Single field
db.users.createIndex({ age: 1 })
// Compound
db.users.createIndex({ city: 1, age: -1 })
// Unique
db.users.createIndex({ email: 1 }, { unique: true })
// Text index
db.articles.createIndex({ title: "text", content: "text" })
// Partial index
db.users.createIndex(
{ age: 1 },
{ partialFilterExpression: { active: true } }
)
// Sparse
db.users.createIndex({ phone: 1 }, { sparse: true })
// TTL (auto-delete after 1 hour)
db.sessions.createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 3600 }
)
// List indexes
db.users.getIndexes()
// Drop index
db.users.dropIndex("age_1")
8. AGGREGATION PIPELINE EXAMPLES
Basic: Filter + Project
db.users.aggregate([
{ $match: { age: { $gte: 30 } } },
{ $project: { name: 1, age: 1, _id: 0 } }
])
Group & Count
db.users.aggregate([
{ $group: { _id: "$city", count: { $sum: 1 } } }
])
Average Age per City
db.users.aggregate([
{ $group: {
_id: "$city",
avgAge: { $avg: "$age" },
totalUsers: { $sum: 1 }
}}
])
Top 2 Cities by User Count
db.users.aggregate([
{ $group: { _id: "$city", count: { $sum: 1 } } },
{ $sort: { count: -1 } },
{ $limit: 2 }
])
Unwind Array
db.users.aggregate([
{ $unwind: "$hobbies" },
{ $group: { _id: "$hobbies", count: { $sum: 1 } } },
{ $sort: { count: -1 } }
])
Lookup (Join)
// Assume orders collection
db.users.aggregate([
{
$lookup: {
from: "orders",
localField: "name",
foreignField: "customer",
as: "orders"
}
},
{ $project: { name: 1, orderCount: { $size: "$orders" } } }
])
Add Computed Field
db.users.aggregate([
{
$addFields: {
isAdult: { $gte: ["$age", 18] },
hobbyCount: { $size: "$hobbies" }
}
}
])
Write Output to New Collection
db.users.aggregate([
{ $match: { active: true } },
{ $out: "active_users" }
])
9. SAMPLE DATA FOR PRACTICE
// Insert sample data
db.products.insertMany([
{ name: "Laptop", price: 1200, category: "Electronics", inStock: true, tags: ["portable", "work"] },
{ name: "Mouse", price: 25, category: "Electronics", inStock: true, tags: ["wireless"] },
{ name: "Book", price: 15, category: "Education", inStock: false, tags: ["paperback"] },
{ name: "Pen", price: 2, category: "Stationery", inStock: true, tags: ["blue", "ballpoint"] }
])
db.orders.insertMany([
{ orderId: "O1", customer: "Alice", items: ["Laptop", "Mouse"], total: 1225, status: "shipped" },
{ orderId: "O2", customer: "Bob", items: ["Book"], total: 15, status: "pending" }
])
10. PRACTICE EXERCISES (Try These!)
-
Find all users older than 28 from Tokyo
js db.users.find({ age: { $gt: 28 }, city: "Tokyo" }) -
Update all inactive users to active
js db.users.updateMany({ active: false }, { $set: { active: true } }) -
Count products in "Electronics" category
js db.products.countDocuments({ category: "Electronics" }) -
Get total sales per customer
js db.orders.aggregate([ { $group: { _id: "$customer", totalSpent: { $sum: "$total" } } } ]) -
Find products with "wireless" tag
js db.products.find({ tags: "wireless" }) -
Add index on
priceand sort descending
js db.products.createIndex({ price: -1 }) db.products.find().sort({ price: -1 }) -
Create TTL index on
createdAt
js db.logs.createIndex({ createdAt: 1 }, { expireAfterSeconds: 86400 })
11. USEFUL SYSTEM COMMANDS
// Server status
db.serverStatus()
// Current operations
db.currentOp()
// Kill long-running op
db.killOp(<opId>)
// Collection stats
db.users.stats()
// Validate collection
db.users.validate()
// Compact (defragment)
db.runCommand({ compact: "users" })
12. MONGOSH TIPS
// Pretty print
.pretty()
// Limit results
.limit(5)
// Count
.count()
// Explain query plan
db.users.find({ age: 30 }).explain("executionStats")
// Clear screen
cls
// Exit
exit
Download This Guide as .js File
// Save as: mongodb-practice.js
// Run: mongosh mongodb-practice.js
use practiceDB
db.dropDatabase()
print("=== INSERTING DATA ===")
db.users.insertMany([...]) // paste all insert commands
print("=== PRACTICE QUERIES ===")
// paste all queries
Resources
You now have 100+ working MongoDB commands!
Copy → Paste → Run → Learn
Next Step: Build a mini project (e.g., Todo App, Blog, Inventory) using these commands.
Want a full project template or Node.js + MongoDB example? Just ask!