8.1 mongosh Scripting & Administrative Commands

Key Takeaways

  • The modern MongoDB Shell (mongosh) is built on a Node.js REPL environment, supporting ECMAScript 2020+, native Promises, top-level async/await, and npm module integration.
  • Startup configuration in ~/.mongoshrc.js enables custom prompts and global helpers, which can be bypassed in automated scripts using the --norc flag.
  • Non-interactive scripting is supported via 'mongosh --file <script.js>' and inline evaluation via 'mongosh --eval', combining with --quiet and --json for CI/CD pipelines.
  • mongosh automatically formats and pretty-prints query results by default and provides 'console.table()' for tabular result visualization.
  • Administrative telemetry commands include 'db.stats()' for database storage, 'db.serverStatus()' for server health, 'db.currentOp()' for active operations, and 'db.killOp(opid)' to terminate runaway queries.
Last updated: September 2026

8.1 mongosh Scripting & Administrative Commands

The MongoDB Shell (mongosh) is the primary interactive command-line interface and JavaScript execution environment for connecting to, querying, configuring, and managing MongoDB databases. Introduced to replace the legacy mongo shell (which was deprecated in MongoDB 5.0 and removed in MongoDB 6.0), mongosh provides a modern developer experience built directly on top of the Node.js runtime environment.

For the MongoDB Certified Associate Developer Exam, developers must thoroughly understand the capabilities of mongosh, including its modern JavaScript language features (ES6+, Promises, top-level await), shell automation and scripting interfaces (--eval, --file, load()), configuration through .mongoshrc.js, output formatting helpers, and critical database telemetry commands (db.stats(), db.collection.stats(), db.serverStatus(), db.currentOp(), and db.killOp()).


1. The Modern mongosh REPL vs. Legacy mongo Shell

The transition from the legacy mongo shell to mongosh represents a fundamental architectural redesign of MongoDB's administrative tooling. While the legacy shell relied on an embedded, heavily customized Mozilla SpiderMonkey or v8 JavaScript engine with limited language feature support, mongosh runs directly inside the Node.js REPL (Read-Eval-Print Loop) architecture.

Core Architectural Advantages of mongosh

  1. Full ECMAScript 2020+ (ES6+) Standard Support: Developers can write modern JavaScript natively, including let and const block scoping, arrow functions, destructuring assignment, default and rest parameters, template literals, optional chaining (?.), nullish coalescing (??), and ES classes.
  2. Top-Level await and Native Promises: In mongosh, asynchronous operations return native JavaScript Promises. Crucially, mongosh supports top-level await directly in the interactive prompt without requiring wrapping code inside asynchronous Immediately Invoked Function Expressions (IIFEs).
  3. npm Package Ecosystem Integration: Because mongosh runs on Node.js, scripts and shell sessions can import and use standard Node.js built-in modules (such as fs, path, crypto, os, and http) as well as external npm packages installed in the local environment via standard require() syntax.
  4. Syntax Highlighting & Intelligent Autocompletion: The modern shell provides dynamic contextual autocompletion for collection names, database commands, field names, and aggregation operators, accompanied by colored syntax highlighting for BSON types.
  5. Embedded Cryptographic & Security Tooling: Native client-side field level encryption (CSFLE) and queryable encryption (QE) helpers are baked into mongosh.

Comparison: mongosh vs. Legacy mongo Shell

Architectural DimensionModern mongoshLegacy mongo Shell (Deprecated/Removed)
Underlying EngineNode.js REPL runtimeEmbedded Mozilla SpiderMonkey C++
JavaScript StandardModern ES2020+ standardsLimited ES5 / partial ES6 subset
Asynchronous ParadigmsNative Promises & top-level awaitBlocking synchronous API / pseudo-callbacks
Top-Level await✅ Supported out of the box in REPL❌ Syntax error (required wrapper functions)
External Module Loadingrequire('lodash'), require('fs')❌ Not supported; only basic load() of JS files
Query Output FormattingAutomatic colorized pretty-printing by defaultUnformatted single-line JSON unless .pretty() called
Telemetry HelpersModern db.collection.stats() / collStatsLegacy db.collection.stats()
Active Support StatusActively developed, standard since MongoDB 5.0+Deprecated in MongoDB 5.0, removed in MongoDB 6.0

Modern JavaScript & Async/Await Examples in mongosh

// 1. Destructuring and Modern ES6 syntax
const { totalAmount, status } = await db.orders.findOne({ orderId: "ORD-9821" });
console.log(`Order status is ${status}, total: $${totalAmount}`);

// 2. Top-level await with Array iteration and Promises
const customerIds = ["CUST-001", "CUST-002", "CUST-003"];
const customerSummaries = await Promise.all(
  customerIds.map(async (id) => {
    const orderCount = await db.orders.countDocuments({ customerId: id });
    const profile = await db.customers.findOne({ _id: id }, { projection: { name: 1 } });
    return { id, name: profile?.name ?? "Unknown", orderCount };
  })
);
console.table(customerSummaries);

// 3. Using Node.js standard library modules inside mongosh scripts
const fs = require("fs");
const path = require("path");
const reportPath = path.join(process.cwd(), "audit-report.json");
const highRiskUsers = await db.users.find({ riskScore: { $gte: 85 } }).toArray();
fs.writeFileSync(reportPath, JSON.stringify(highRiskUsers, null, 2));
print(`Audit report exported successfully to ${reportPath}`);

2. Shell Configuration: .mongoshrc.js

When mongosh starts, it searches for a startup configuration file named .mongoshrc.js in the user's home directory (~/.mongoshrc.js on Linux/macOS or %USERPROFILE%\.mongoshrc.js on Windows). If found, mongosh executes the JavaScript code in this file before presenting the prompt to the user.

Common Use Cases for .mongoshrc.js

  1. Customizing the Shell Prompt: Setting the global prompt variable to a custom function allows dynamic display of the current database, connected user, host, replica set primary/secondary status, or latency.
  2. Defining Global Utility Functions: Helper functions added to globalThis or the db prototype are immediately available in every interactive session.
  3. Setting Operational Safety Guards: Overriding dangerous destructive commands (such as db.dropDatabase()) in production connection strings to require explicit confirmation.
  4. Setting Default Options: Configuring default output limits, telemetry display preferences, or formatting styles.
// Sample ~/.mongoshrc.js Configuration File

// 1. Dynamic, Informative Shell Prompt showing DB and Replica Set Status
prompt = () => {
  const dbName = db.getName();
  let status = "standalone";
  
  try {
    const isMaster = db.isMaster();
    if (isMaster.setName) {
      status = isMaster.ismaster ? "PRIMARY" : isMaster.secondary ? "SECONDARY" : "OTHER";
    }
  } catch (e) {
    status = "disconnected";
  }
  
  return `[mongosh] ${dbName}@${status} > `;
};

// 2. Global Helper for Quick Collection Summary
globalThis.quickSummary = async function(collName) {
  const count = await db[collName].estimatedDocumentCount();
  const stats = await db[collName].stats();
  print(`--- Collection Summary: ${collName} ---`);
  print(`Estimated Document Count: ${count.toLocaleString()}`);
  print(`Total Storage Size:       ${(stats.storageSize / (1024 * 1024)).toFixed(2)} MB`);
  print(`Total Index Size:         ${(stats.totalIndexSize / (1024 * 1024)).toFixed(2)} MB`);
};

// 3. Operational Safety Warning
print("=== Custom .mongoshrc.js loaded successfully ===");

Bypassing Configuration: The --norc Flag

In automated environments, CI/CD pipelines, or debugging scenarios where user customizations could alter expected script behavior or slow down connection startup, pass the --norc command-line flag:

# Launch mongosh without executing ~/.mongoshrc.js
mongosh "mongodb://localhost:27017/analytics" --norc

3. Output Formatting & Visual Inspection

One of the most immediate quality-of-life improvements in mongosh is output presentation.

Automatic Pretty-Printing vs. .pretty()

In the legacy mongo shell, executing db.users.find() returned raw, single-line unformatted JSON strings that were difficult to read. Developers had to append .pretty() to format documents across multiple indented lines.

In mongosh, all query results and BSON documents are automatically pretty-printed and colorized by default. The .pretty() method still exists in mongosh purely for backward compatibility with legacy scripts, but calling it is completely redundant and acts as a no-op.

// In mongosh, these two commands produce identical, fully formatted output:
db.users.find({ status: "ACTIVE" });
db.users.find({ status: "ACTIVE" }).pretty(); // .pretty() is a no-op in mongosh

Tabular Visualization with console.table()

mongosh includes the standard browser/Node.js console.table() method, which renders arrays of objects or cursor documents in a clean, column-aligned ASCII grid:

// Retrieve top 5 recent orders and display in a tabular grid
const recentOrders = await db.orders.find(
  {},
  { projection: { orderId: 1, customerId: 1, totalAmount: 1, status: 1, _id: 0 } }
).sort({ createdAt: -1 }).limit(5).toArray();

console.table(recentOrders);

Output:

┌─────────┬────────────┬──────────────┬─────────────┬─────────────┐
│ (index) │  orderId   │  customerId  │ totalAmount │   status    │
├─────────┼────────────┼──────────────┼─────────────┼─────────────┤
│    0    │ 'ORD-1091' │ 'CUST-841'   │    184.5    │ 'COMPLETED' │
│    1    │ 'ORD-1090' │ 'CUST-219'   │    42.0     │ 'PENDING'   │
│    2    │ 'ORD-1089' │ 'CUST-554'   │    915.2    │ 'SHIPPED'   │
│    3    │ 'ORD-1088' │ 'CUST-102'   │    12.75    │ 'COMPLETED' │
│    4    │ 'ORD-1087' │ 'CUST-993'   │    310.0    │ 'CANCELLED' │
└─────────┴────────────┴──────────────┴─────────────┴─────────────┘

4. Script Execution Modes: Non-Interactive & Automated Execution

mongosh supports both interactive ad-hoc usage and non-interactive scripted execution for DevOps automation, database migrations, and operational maintenance.

1. File-Based Execution: mongosh --file <script.js>

To execute an external JavaScript file non-interactively, pass the --file flag or provide the script path directly as a positional argument:

# Execute migration script non-interactively and exit
mongosh "mongodb://cluster0.example.com:27017/prodDB" --file ./migrations/v2_indexing.js

# Alternative positional syntax
mongosh "mongodb://cluster0.example.com:27017/prodDB" ./migrations/v2_indexing.js

Inside an active interactive session, you can also load and execute external scripts on demand using the load() helper:

// Executed inside an interactive mongosh session:
load("/Users/admin/scripts/seed_test_data.js");

2. Inline Code Evaluation: mongosh --eval "<code/command>"

The --eval parameter executes a snippet of JavaScript or a database command directly from the operating system shell and terminates immediately upon completion. When combined with --quiet (which suppresses connection banners and telemetry headers) and --json, it allows seamless parsing inside shell pipelines (e.g., with jq):

# Check cluster ping status from bash script
mongosh "mongodb://localhost:27017/admin" --quiet --eval "db.runCommand({ ping: 1 })"

# Extract current connection count in JSON format for external monitoring systems
ACTIVE_CONNS=$(mongosh "mongodb://localhost:27017/admin" --quiet --eval "JSON.stringify(db.serverStatus().connections)")
echo "Active connections: $ACTIVE_CONNS"

Exit Codes and Error Handling in Scripts

In mongosh scripts, exceptions bubble up to the Node.js process. You can manage exit statuses programmatically using standard JavaScript try...catch blocks and process.exit(code):

// deploy-indexes.js
try {
  print("Creating compound index on orders...");
  const result = await db.orders.createIndex(
    { customerId: 1, orderDate: -1 },
    { name: "idx_customer_date" }
  );
  print(`Index build successful: ${result}`);
  process.exit(0); // Exit code 0 indicates success
} catch (error) {
  console.error(`Index build failed with error: ${error.message}`);
  process.exit(1); // Non-zero exit code signals failure to CI/CD pipeline
}

5. Administrative Commands & Database Telemetry Helpers

Database administrators and developers frequently rely on built-in administrative helpers to evaluate database capacity, inspect physical storage allocations, analyze server health, and manage active operations.

1. Database Storage Metrics: db.stats()

The db.stats() helper returns a document detailing the storage footprint, object counts, and index sizes for the currently selected database.

// Basic usage (values in bytes by default)
db.stats();

// Specify a scale factor (e.g., 1024 * 1024 for megabytes)
db.stats(1024 * 1024);
// Alternatively, pass an options document:
db.stats({ scale: 1048576 });

Key Fields in db.stats() Output:

  • db: The name of the database.
  • collections: Total number of collections in the database.
  • views: Total number of views.
  • objects: Total number of BSON documents stored across all collections.
  • avgObjSize: Average document size in bytes.
  • dataSize: The total uncompressed size of all BSON documents in memory/storage.
  • storageSize: The total physical disk space allocated to collections by the WiredTiger storage engine (reflects block compression).
  • indexes: Total count of indexes across all collections.
  • indexSize: Total physical disk space consumed by all B-tree indexes.
  • freeStorageSize: Pre-allocated storage space within the data files that is currently free and available for reuse by WiredTiger.
  • totalSize: Sum of storageSize + indexSize (the complete physical footprint of the database on disk).
+-----------------------------------------------------------------------------+
|                        Database Storage Hierarchy                           |
|                                                                             |
|  [ dataSize ]       : Raw uncompressed BSON document bytes                  |
|  [ storageSize ]    : Compressed on-disk collection extents                 |
|  [ indexSize ]      : On-disk B-tree index extents                          |
|  [ totalSize ]      : storageSize + indexSize (Total disk footprint)        |
|  [ freeStorageSize ]: Pre-allocated uncompressed extent space inside files  |
+-----------------------------------------------------------------------------+

2. Collection Storage Metrics: db.collection.stats() / collStats

To inspect a single collection's physical storage, index overhead, and WiredTiger engine statistics, use db.collection.stats() (or the database command db.runCommand({ collStats: "collectionName" })).

// Retrieve collection statistics in Megabytes
db.orders.stats(1024 * 1024);

Critical Collection Metrics:

  • count: Exact document count in the collection.
  • size: Uncompressed data size of all documents in the collection.
  • storageSize: Compressed on-disk size of the collection.
  • nindexes: Number of indexes on the collection.
  • totalIndexSize: Combined disk space consumed by all indexes.
  • indexSizes: Document breaking down the size of each individual index by name (e.g., { "_id_": 143360, "idx_customer_date": 81920 }). This is invaluable for identifying oversized or unused indexes.
  • capped: Boolean indicating whether the collection is a fixed-size Capped Collection.

3. Server Health & Telemetry: db.serverStatus()

The db.serverStatus() command returns a massive, comprehensive telemetry document providing an instant snapshot of the mongod process state, resource utilization, and operational throughput.

// Query global server telemetry
const status = db.serverStatus();

Essential Sub-Documents in db.serverStatus():

  1. connections: Tracks current client connection load:
    • current: Number of active incoming client connections.
    • available: Remaining connection slots before reaching maxConns.
    • totalCreated: Cumulative total of connection sockets accepted since server boot.
  2. opcounters: Cumulative count of CRUD operations executed since startup:
    • insert, query, update, delete, getmore, command.
  3. mem: Memory utilization reported by the operating system:
    • resident: Physical RAM currently occupied by mongod (in MB).
    • virtual: Total virtual address space allocated (in MB).
  4. wiredTiger.cache: Granular internal storage engine cache telemetry:
    • bytes currently in the cache: RAM allocated to the WiredTiger working set.
    • maximum bytes configured: Configured cache ceiling (defaults to ~50% of RAM - 1GB).
    • tracked dirty bytes in the cache: Modified data in RAM waiting to be flushed to disk.
  5. globalLock.currentQueue: Number of operations currently waiting to acquire a lock (readers and writers). A persistently non-zero queue signals severe I/O or locking bottlenecks.

4. Inspecting Active Operations: db.currentOp()

The db.currentOp() administrative helper inspects in-flight database operations currently executing or queued on the mongod instance. It is the primary tool for diagnosing slow queries, locking conflicts, and unindexed runaway operations in real time.

// Basic usage: returns all in-flight operations
db.currentOp();

// Filtered query: Find unindexed user operations running longer than 5 seconds
db.currentOp({
  "active": true,
  "secs_running": { $gte: 5 },
  "op": { $in: ["query", "update", "remove", "command"] },
  "ns": { $ne: "local.oplog.rs" } // Exclude internal replication ops
});

Crucial Fields in currentOp Entries:

  • opid: Unique 32-bit or 64-bit integer identifier for the operation. Required to kill the operation.
  • secs_running: Duration in seconds that the operation has been executing.
  • microsecs_running: Duration in microseconds.
  • op: The type of operation (query, insert, update, remove, getmore, command).
  • ns: Target namespace (<database>.<collection>).
  • command: The complete query filter, update expression, or command payload submitted by the client.
  • planSummary: The query execution plan (e.g., "COLLSCAN", "IXSCAN { customerId: 1 }"). Seeing "COLLSCAN" on a query running for many seconds immediately identifies a missing index.
  • numYields: Number of times the operation yielded its lock to allow other operations to execute.
  • client: Client IP address and port that originated the request.

5. Terminating Problematic Operations: db.killOp()

When an unindexed query or rogue aggregation saturates CPU, consumes excessive RAM, or blocks critical writes, administrators can terminate the operation immediately using db.killOp(opid).

// Step 1: Identify the problematic operation ID
const slowOps = db.currentOp({ "secs_running": { $gte: 10 }, "op": "query" });
const targetOpId = slowOps.inprog[0].opid;

// Step 2: Kill the specific operation by its opid
db.killOp(targetOpId);
// Returns: { info: "attempting to kill op", ok: 1 }

[!WARNING] Operational Safety with killOp: Never execute db.killOp() on internal background system operations (such as replication sync threads on local.oplog.rs, TTL collection monitors, or checkpoint threads), as doing so can destabilize replica set consensus or cause instance termination. Always filter db.currentOp() by namespace (ns) or client IP before killing operations.

Loading diagram...
mongosh Execution Flow, Architecture & Administrative Telemetry Stack
Test Your Knowledge

Which of the following statements accurately characterizes the architectural capabilities of the modern MongoDB Shell (mongosh) compared to the legacy mongo shell?

A
B
C
D
Test Your Knowledge

A DevOps engineer wants to run an automated maintenance script on a production cluster without executing any local custom prompt customizations or environment overrides configured in ~/.mongoshrc.js. Which command should they execute?

A
B
C
D
Test Your Knowledge

During a production incident, database performance degrades severely due to an unindexed query executing a full collection scan across 50 million documents. What is the correct sequence of administrative commands in mongosh to locate and immediately abort this specific query?

A
B
C
D
Test Your Knowledge

An administrator examines the output of db.stats(1024 * 1024) and notes that dataSize is 850 MB, storageSize is 320 MB, and freeStorageSize is 45 MB. How should these metrics be interpreted regarding the WiredTiger storage engine?

A
B
C
D