MongoDB Command Reference

By this point in the course you have learned individual MongoDB features one at a time – queries, updates, aggregation, indexes, replication. This lesson is different: it is a reference, a single page that groups the commands you will reach for constantly in mongosh so you don’t have to hunt back through earlier lessons. Keep it bookmarked. It also clarifies a subtlety that trips up almost every new MongoDB user: some things you type in mongosh are real JavaScript, and some are shell-only shortcuts that only work interactively.

Overview / How mongosh commands actually work

mongosh is a JavaScript REPL (read-eval-print loop) with a MongoDB driver built in. When you type db.users.find({ status: "active" }), you are writing and executing a real JavaScript expression: db is a JavaScript object representing the current database, .users is a property access that returns a collection object, and .find(...) is a real method call that returns a cursor object. This is why you can chain methods (.find().sort().limit()), store results in variables (const cur = db.orders.find()), and write loops and conditionals around your queries – it is all just JavaScript running against a live connection.

However, mongosh also layers a handful of shell-only convenience shortcuts on top of that JavaScript engine, borrowed from the older mongo shell for muscle-memory compatibility: use <dbname>, show dbs, show collections, show users, and exit. These are not JavaScript statements – use mydb would be a syntax error if you tried to run it inside a .js file with Node.js, because use isn’t a JavaScript keyword and mydb isn’t a declared variable. mongosh special-cases these exact strings when you type them at the interactive prompt. Know the split: if you’re writing a reusable script (a .mongosh.js file, a Node.js app, a migration script), use the real JavaScript equivalents (db.getSiblingDB("mydb"), db.getCollectionNames()) instead of the shortcuts.

Every command in mongosh ultimately does one of three things: it inspects metadata (what databases/collections/indexes exist, how big they are), it performs a CRUD or aggregation operation against documents, or it issues an admin command to the server (replica set status, current operations, server configuration). Admin commands are frequently just JavaScript-friendly wrappers around db.runCommand({...}) or db.adminCommand({...}), which sends a raw BSON command document to the server – useful to know because if a helper method (like rs.status()) doesn’t exist for something you need, you can usually still reach it with db.adminCommand({ ... }) directly.

Syntax

There isn’t one single syntax form for “a command” since this lesson spans several categories, but the general shapes are:

// Shell-only shortcut (interactive only, not JS)
use <dbname>

// Collection method call (real JavaScript)
db.<collection>.<method>(<args>)

// Database-level helper (real JavaScript)
db.<helperMethod>(<args>)

// Raw admin/database command (real JavaScript)
db.runCommand({ <commandName>: 1, ...options })
db.adminCommand({ <commandName>: 1, ...options })
  • <dbname> – the database to switch the shell’s context to; it does not need to exist yet, it is created lazily on first write.
  • <collection> – the collection name, e.g. users, orders.
  • <method> – a CRUD/query/index/aggregation method such as find, insertOne, updateMany, createIndex, aggregate.
  • runCommand / adminCommand – the low-level escape hatch; adminCommand always runs against the admin database regardless of current context (needed for cluster-wide commands like listDatabases).

Examples

Example 1: Shell navigation shortcuts

use shop
show collections
show dbs

Output:

switched to db shop
orders
products
users
admin        0.000GB
config       0.000GB
local        0.000GB
shop         0.011GB

This is the first thing most people type in a new mongosh session: switch into the working database, then list what’s inside it. Note that show dbs only lists databases that actually contain data (or system databases) – a database you just used but haven’t written to yet won’t appear until you insert something.

Example 2: Basic CRUD reference in context

db.users.insertOne({ name: "Priya Shah", email: "priya@example.com", active: true });
db.users.find({ active: true }).limit(2);
db.users.updateOne({ email: "priya@example.com" }, { $set: { active: false } });
db.users.deleteOne({ email: "priya@example.com" });

Output:

{
  acknowledged: true,
  insertedId: ObjectId("66b1f0a1c3d4e5f6a7b8c9d0")
}
[
  { _id: ObjectId("66b1f0a1c3d4e5f6a7b8c9d0"), name: "Priya Shah", email: "priya@example.com", active: true }
]
{ acknowledged: true, matchedCount: 1, modifiedCount: 1 }
{ acknowledged: true, deletedCount: 1 }

These four methods – insertOne/insertMany, find, updateOne/updateMany, and deleteOne/deleteMany – cover the vast majority of daily work and were covered in depth earlier in the course; they’re listed here as the reference anchor point.

Example 3: Diagnostic and admin commands

db.orders.createIndex({ customerId: 1, orderDate: -1 });
db.orders.find({ customerId: 501 }).sort({ orderDate: -1 }).explain("executionStats");
db.orders.getIndexes();
db.orders.stats();
db.serverStatus().connections;

Output:

customerId_1_orderDate_-1
{
  queryPlanner: { winningPlan: { stage: "FETCH", inputStage: { stage: "IXSCAN", indexName: "customerId_1_orderDate_-1" } } },
  executionStats: { executionSuccess: true, nReturned: 12, totalDocsExamined: 12 }
}
[
  { v: 2, key: { _id: 1 }, name: "_id_" },
  { v: 2, key: { customerId: 1, orderDate: -1 }, name: "customerId_1_orderDate_-1" }
]
{ ns: "shop.orders", count: 48213, size: 6291200, avgObjSize: 130, nindexes: 2 }
{ current: 14, available: 51186, totalCreated: 92 }

This chains a normal index-creation call with three read-only diagnostic calls: explain() to confirm the query planner picked IXSCAN instead of a full COLLSCAN, getIndexes() to list every index actually built on the collection, stats() for size/document counts, and serverStatus() for live server metrics like open connection counts – invaluable when diagnosing “why is this slow” or “why is this connection pool exhausted” issues.

How it works step by step

When you press Enter in mongosh, one of three things happens. First, if the line matches a known shell shortcut (use, show ..., exit) it is intercepted by the shell’s own parser before ever reaching the JavaScript engine, and it manipulates the shell’s local session state (like which database db currently points to). Second, if it’s a JavaScript expression, it is evaluated by the embedded JS engine; any call on db or a collection object builds a wire-protocol command message, sends it over the current connection to mongod (or mongos for a sharded cluster), waits for the BSON response, and converts it back into a JavaScript object that gets printed. Third, for `runCommand`/`adminCommand`, the JS layer is bypassed almost entirely – you’re constructing the raw command document yourself, and the server just executes it as-is. For queries specifically, the server-side query planner examines your filter, checks available indexes, and (unless the query is trivial) runs a short competition between candidate plans, caching the winner so future identical-shaped queries skip re-planning – which is exactly what explain("executionStats") lets you inspect.

Common Mistakes

Mistake 1: Using a shell shortcut inside a script file.

// WRONG - this is not valid JavaScript, it will throw a SyntaxError
// inside a .mongosh.js file or a Node.js script
use shop
db.users.find();

Shortcuts like use only exist in the interactive prompt’s special-cased parser. In any script, connect explicitly and switch databases with real JavaScript:

const shopDb = db.getSiblingDB("shop");
shopDb.users.find();

Mistake 2: Comparing an _id to a plain string.

// WRONG - idFromUrl is a string like "66b1f0a1c3d4e5f6a7b8c9d0",
// but _id is stored as an ObjectId, so this matches nothing
const idFromUrl = "66b1f0a1c3d4e5f6a7b8c9d0";
db.users.find({ _id: idFromUrl });

A string and an ObjectId are different BSON types and never compare equal, even when their printed text matches. Convert explicitly:

db.users.find({ _id: new ObjectId(idFromUrl) });

Mistake 3: Reaching for updateOne when every matching document should change. If you intend to flip a flag on every document matching a filter and write db.orders.updateOne({ status: "pending" }, { $set: { status: "cancelled" } }), only the single first-matched document is updated – the rest silently stay pending. Use updateMany whenever the intent is “every matching document.”

Best Practices

  • Use explain("executionStats") before assuming a slow query needs code changes – check for COLLSCAN first.
  • Reserve the shell-only shortcuts (use, show dbs, etc.) for interactive exploration; write real JavaScript (db.getSiblingDB(), db.getCollectionNames()) in any file that gets saved or reused.
  • Run db.collection.help() or db.help() directly in mongosh when you forget a method name – it lists every available method with a short description, straight from your connected server’s version.
  • Prefer adminCommand over runCommand for cluster-wide operations (like listDatabases) so you don’t have to worry about which database is currently selected.
  • Check db.serverStatus() and rs.status() (on a replica set) periodically in production troubleshooting – most “MongoDB is slow” incidents show up in connection counts, replication lag, or lock percentages before anything else.
  • Use mongodump/mongorestore (real shell/OS commands, not mongosh commands) for backups – don’t try to script backups from inside mongosh itself.

Practice Exercises

Exercise 1: In mongosh, switch into a database called library, list its collections, then use the JavaScript equivalent (db.getSiblingDB) to do the same switch without the shortcut. Confirm both approaches leave you querying the same data.

Exercise 2: On any collection with at least a few hundred documents, run a find() with a filter on an unindexed field, call .explain("executionStats"), and note the stage value. Then create an index on that field and re-run explain – the stage should change from COLLSCAN to IXSCAN and totalDocsExamined should drop.

Exercise 3: Write one line using db.runCommand that returns the same result as db.stats() without calling the stats() helper method (hint: the underlying command is named dbStats).

Summary

  • mongosh is a real JavaScript REPL – most commands you type are genuine JS method calls against db and collection objects.
  • A small set of commands (use, show dbs, show collections, show users, exit) are interactive-only shortcuts and are not valid JavaScript – never use them in scripts.
  • CRUD methods (insertOne/insertMany, find, updateOne/updateMany, deleteOne/deleteMany) cover most daily work.
  • explain(), getIndexes(), stats(), and serverStatus() are your primary diagnostic tools for performance troubleshooting.
  • db.runCommand() and db.adminCommand() are low-level escape hatches that let you issue any server command directly, even ones without a dedicated helper method.
  • Always convert a string _id to new ObjectId(str) before querying by it.