Installing MongoDB and Using mongosh: Getting Started Guide
Install MongoDB Community Edition on Linux, macOS, and Windows. Connect with mongosh, navigate databases, and run your first queries. Lesson 2 of the MongoDB & NoSQL Mastery course.

MongoDB Community Edition is free, open-source, and available on every major platform. mongosh — the MongoDB Shell — replaced the legacy mongo shell in MongoDB 6 and provides a full JavaScript/Node.js environment with syntax highlighting, command history, and tab completion. This lesson gets both running and covers the shell commands you will use throughout this course.
Previous: Lesson 1 — What Is NoSQL?
Installation Options
Option A: Install on Ubuntu / Debian
# Import the MongoDB GPG key
curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc \
| sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmor
# Add the MongoDB repository
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] \
https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" \
| sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
# Install
sudo apt update
sudo apt install -y mongodb-org
# Start and enable the service
sudo systemctl start mongod
sudo systemctl enable mongod
# Verify
sudo systemctl status mongodOption B: Install on macOS (Homebrew)
brew tap mongodb/brew
brew update
brew install mongodb-community@7.0
# Start as a background service
brew services start mongodb-community@7.0Option C: Run via Docker (Recommended for Development)
# Pull and run MongoDB 7 — data persisted to a named volume
docker run -d \
--name mongodb \
-p 27017:27017 \
-e MONGO_INITDB_ROOT_USERNAME=admin \
-e MONGO_INITDB_ROOT_PASSWORD=secret \
-v mongodb_data:/data/db \
mongo:7.0
# Verify it's running
docker ps
docker logs mongodbOption D: MongoDB Atlas Free Tier
For a cloud instance with no local setup:
- Go to and create a free account
- Create a free M0 cluster (512MB, shared)
- Add your IP to the network access list
- Create a database user
- Copy the connection string — use it in mongosh with
mongosh "mongodb+srv://..."
Connecting with mongosh
# Connect to a local MongoDB instance (no auth)
mongosh
# Connect with authentication
mongosh "mongodb://admin:secret@localhost:27017/admin"
# Connect to Atlas
mongosh "mongodb+srv://username:password@cluster0.abc123.mongodb.net/mydb"
# Connect with explicit options
mongosh --host localhost --port 27017 -u admin -p secret --authenticationDatabase adminOn a successful connection you will see the mongosh prompt:
Current Mongosh Log ID: 665a1234abc
Connecting to: mongodb://localhost:27017/
Using MongoDB: 7.0.x
Using Mongosh: 2.x.x
test>Navigating Databases and Collections
MongoDB organises data into databases → collections → documents. A database is created automatically the first time you write data to it.
// Show all databases
show dbs
// Switch to (or create) a database
use myapp
// Show current database
db
// Show collections in the current database
show collections
// Drop the current database (destructive — use with care)
db.dropDatabase()Essential mongosh Commands
Database Stats
// Database storage statistics
db.stats()
// Collection statistics
db.users.stats()
// Server status (uptime, connections, opcounters)
db.serverStatus()Collection Operations
// Create a collection explicitly (optional — also created on first insert)
db.createCollection("products")
// List all collections with details
db.getCollectionInfos()
// Rename a collection
db.products.renameCollection("items")
// Drop a collection
db.products.drop()Running Your First Insert and Find
// Insert a single document
db.users.insertOne({
name: "Alice Nguyen",
email: "alice@example.com",
role: "admin",
createdAt: new Date()
})
// Find all documents in a collection
db.users.find()
// Pretty-print (mongosh does this by default)
db.users.find().pretty()
// Count documents
db.users.countDocuments()The mongosh JavaScript Environment
mongosh is a full JavaScript REPL. You can define variables, write loops, and use Node.js built-ins:
// Variables
const db_name = db.getName()
print("Connected to:", db_name)
// Loops
for (let i = 1; i <= 5; i++) {
db.test.insertOne({ index: i, created: new Date() })
}
// Functions
function dropIfExists(collectionName) {
const exists = db.getCollectionNames().includes(collectionName)
if (exists) {
db[collectionName].drop()
print(`Dropped collection: ${collectionName}`)
} else {
print(`Collection does not exist: ${collectionName}`)
}
}
dropIfExists("test")
// Use JavaScript date arithmetic
const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)
db.sessions.find({ createdAt: { $lt: thirtyDaysAgo } }).count()mongosh Configuration and .mongoshrc.js
Create ~/.mongoshrc.js to customise your mongosh session — set default database, define helper functions, configure the prompt:
// ~/.mongoshrc.js
// Custom prompt showing host and database
prompt = () => `${db.getMongo().host}/${db.getName()}> `
// Helper shortcuts
const show_indexes = (coll) => db[coll].getIndexes().forEach(printjson)
const count = (coll) => db[coll].countDocuments()
const recent = (coll, n = 5) => db[coll].find().sort({ _id: -1 }).limit(n).toArray()MongoDB Compass: The GUI Alternative
MongoDB Compass is the official graphical interface. It is useful for:
- Exploring collection structure and document shapes visually
- Building and testing aggregation pipelines with a stage-by-stage editor
- Analysing query performance and index usage
- Importing and exporting data as JSON or CSV
Compass connects with the same connection string as mongosh. Both tools are useful: mongosh for scripting and automation, Compass for exploration and pipeline development.
