For years, database administrators interacting with MongoDB on Linux relied on the legacy mongo shell. However, starting with MongoDB 5.0 and 6.0, MongoDB completely deprecated the legacy shell in favor of mongosh (The MongoDB Shell). Re-engineered from the ground up as a modern Node.js-based runtime environment, mongosh provides intelligent autocompletion, syntax highlighting, integrated error debugging, and full ECMAScript 2022 compatibility.
This guide demonstrates how to install mongosh across modern Linux distributions, configure encrypted connections, execute advanced aggregation pipelines, and leverage modern JavaScript scripting directly from the Linux terminal.
Installing mongosh on Linux
On Ubuntu / Debian
# Import official MongoDB public 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 repository source
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/ubuntu $(lsb_release -cs)/mongodb-org/7.0 multiverse" | \
sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
# Install mongosh
sudo apt update && sudo apt install mongodb-mongosh -y
On Fedora / RHEL
sudo dnf install -y mongodb-mongosh
Connecting to MongoDB Instances
1. Local Connection
mongosh
Defaults to connecting to mongodb://127.0.0.1:27017.
2. Authenticated Remote Connection
mongosh "mongodb://dbadmin:[email protected]:27017/analytics?authSource=admin"
Core Database Administration Workflows
1. Querying Collections with Formatted Previews
Unlike the legacy shell which dumped unformatted JSON strings, mongosh formats returned documents with distinct color-coded data types (Dates, ObjectIDs, Strings, Numbers):
use production;
db.users.find({ status: "active" }).limit(5);
2. Running Aggregation Pipelines Interactively
Benefit from multi-line editing and tab completion for aggregation operators:
db.orders.aggregate([
{ $match: { completed: true } },
{ $group: { _id: "$customer_id", totalSpend: { $sum: "$amount" } } },
{ $sort: { totalSpend: -1 } },
{ $limit: 10 }
]);
3. Executing Standalone Automation Scripts
Execute external JavaScript automation scripts directly without entering the interactive prompt:
mongosh "mongodb://localhost:27017/analytics" --file maintenance_cleanup.js
Comparison: Legacy mongo Shell vs Modern mongosh
| Feature | Legacy mongo Shell | Modern mongosh |
|---|---|---|
| Runtime Engine | Custom SpiderMonkey engine | Modern Node.js runtime |
| Autocompletion | Basic command completion | Intelligent context-aware schema & method completion |
| Syntax Highlighting | None (Plain monochrome text) | Rich ANSI color-coded formatting |
| Package Ecosystem | Restricted built-ins | Can require Node.js npm modules natively |