Learn how to use MongoDB Shell (mongosh) with step-by-step commands, CRUD operations, aggregation, performance analysis, transactions, and replica set configuration.
Introduction:
The MongoDB Shell, officially known as mongosh, is the modern command-line interface used to interact with MongoDB databases. It provides a JavaScript-based environment that allows us to query data, manage collections, create indexes, analyze performance, and execute administrative operations.
In this guide, we walk through practical usage of MongoDB Shell, from fundamental commands to advanced production-level operations.
What Is MongoDB Shell (mongosh)?
mongosh is the official replacement for the legacy mongo shell. It offers:
- A modern JavaScript runtime
- Improved error handling
- Better compatibility with new MongoDB features
- Secure connection handling
- Production-ready operational tooling
It supports:
- Local MongoDB servers
- Remote database servers
- MongoDB Atlas clusters
- Replica sets and sharded clusters
For modern environments, mongosh is the recommended CLI interface.
Prerequisites
Before we begin, ensure we have the following:
- An Ubuntu 24.04 on dedicated server or KVM VPS.
- Basic Linux Command Line Knowledge.
- MongoDB installed in the server.
Learn how to use MongoDB Shell (mongosh) with step-by-step commands.
Step 1: Connect to MongoDB
Connect to Local MongoDB
mongosh
Default connection:
mongodb://127.0.0.1:27017
Connect to Remote Server
mongosh "mongodb://username:password@remote_host:27017/database"
Connect to MongoDB Atlas
mongosh "mongodb+srv://username:password@cluster.mongodb.net/database"
Use secure authentication and TLS in production environments.
Step 2: View Databases
show dbs
Check active database:
db
MongoDB creates databases only when data is inserted.
Step 3: Create or Switch Database
use company_db
Confirm:
db
Step 4: Create Collection
Explicit:
db.createCollection("employees")
Implicit (auto-created on insert):
Collections are created automatically when inserting data.
Step 5: Insert Documents
Insert One
db.employees.insertOne({
name: "Rahul Sharma",
role: "Backend Developer",
experience: 4,
active: true
})
Insert Many
db.employees.insertMany([
{ name: "Anita Rao", role: "DevOps Engineer", experience: 6 },
{ name: "Vikram Patel", role: "Frontend Developer", experience: 3 }
])
Step 6: Query Documents
Find All
db.employees.find()
Pretty Format:
db.employees.find().pretty()
Filter Query
db.employees.find({ role: "Backend Developer" })
Comparison Operator
db.employees.find({ experience: { $gt: 3 } })
Common operators:
- $gt
- $lt
- $gte
- $lte
- $ne
- $in
Step 7: Update Documents
Update One
db.employees.updateOne(
{ name: "Rahul Sharma" },
{ $set: { experience: 5 } }
)
Update Many
db.employees.updateMany(
{ active: true },
{ $set: { status: "verified" } }
)
Common update operators:
- $set
- $unset
- $inc
- $push
Step 8: Create Indexes for Performance
Create Index
db.employees.createIndex({ name: 1 })
Descending index:
db.employees.createIndex({ experience: -1 })
View indexes:
db.employees.getIndexes()
Index strategy significantly impacts performance and scalability.
Step 9: Show Collections
show collections
Advanced MongoDB Shell Usage
Now we move beyond basic CRUD into production-level capabilities.
Step 10: Aggregation Pipeline for Data Processing
The aggregation framework allows multi-stage data transformation and analytics.
Group Employees by Role and Calculate Metrics
db.employees.aggregate([
{
$group: {
_id: "$role",
avgExperience: { $avg: "$experience" },
totalEmployees: { $sum: 1 }
}
},
{
$sort: { avgExperience: -1 }
}
])
This pipeline:
- Groups documents by role
- Calculates average experience
- Counts employees
- Sorts results
Aggregation is used in reporting dashboards, analytics engines, and data pipelines.
Step 11: Analyze Query Performance Using explain()
Performance tuning is essential for production systems.
db.employees.find({ role: "Backend Developer" }).explain("executionStats")
Important fields:
- executionTimeMillis
- totalDocsExamined
- totalKeysExamined
- winningPlan
If many documents are scanned without index usage, performance optimization is required.
After creating index:
db.employees.createIndex({ role: 1 })
Run explain again and compare execution statistics.
This is how we validate scalability.
Step 12: Transactions for Data Consistency
Edit MongoDB Configuration
Ubuntu / Debian:
/etc/mongod.conf
AlmaLinux / RHEL:
/etc/mongod.conf
Find or add this section:
replication:
replSetName: "rs0"
Save the file.
restart MongoDB Again
sudo systemctl restart mongod
Initialize the Replica Set
mongosh
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "127.0.0.1:27017" }
]
})
Now check:
rs.status()
MongoDB supports ACID transactions in replica set deployments.
Start session:
const session = db.getMongo().startSession();
Start transaction:
session.startTransaction();
Perform operations:
const employees = session.getDatabase("company_db").employees;
employees.insertOne({ name: "Amit", role: "Manager" });
employees.updateOne(
{ name: "Rahul Sharma" },
{ $set: { role: "Senior Backend Developer" } }
);
Commit transaction:
session.commitTransaction();
session.endSession();
Abort if required:
session.abortTransaction();
Transactions are critical in financial systems, booking platforms, and inventory management systems.
Administrative Commands
Delete Documents
db.employees.deleteOne({ name: "Vikram Patel" })
Delete Many
db.employees.deleteMany({ active: false })
Deletion should always be handled cautiously in production systems.
Drop Collection or Database
Drop collection:
db.employees.drop()
Drop database:
db.dropDatabase()
These operations are irreversible.
Check Server Version
db.version()
Server Status
db.serverStatus()
Connection Status
db.runCommand({ connectionStatus: 1 })
Exit MongoDB Shell
exit
Or press Ctrl + D.
Best Practices for Using MongoDB Shell
- Enable authentication in production
- Avoid destructive commands without confirmation
- Create indexes before scaling traffic
- Use replica sets for high availability
- Regularly back up databases
- Validate performance using explain()
- Use transactions where data integrity is critical
When to Use MongoDB Shell
The MongoDB Shell is ideal for:
- Debugging and troubleshooting
- Performance testing
- Running maintenance commands
- Executing administrative operations
- Automation scripting
- Development environment validation
For application integration, official MongoDB drivers should be used.
Final Summary
The MongoDB Shell (mongosh) is a powerful operational tool that allows direct and structured interaction with MongoDB environments. From basic document management to aggregation pipelines, performance analysis, and transactions, it provides full control over database operations.
When used with discipline and proper understanding, mongosh becomes an essential part of backend development, DevOps workflows, and database administration.
Understanding both foundational commands and advanced capabilities ensures that we operate MongoDB with confidence, scalability, and reliability.
