mongosh Basics: Working in the MongoDB Shell

Beginner
10 min

mongosh Basics: Working in the MongoDB Shell

mongosh is the official MongoDB Shell: a JavaScript REPL that connects to any MongoDB deployment and lets you run queries, administer databases and script repetitive tasks. Everything you do in later lessons — inserts, queries, index creation, aggregation — can be typed straight into it. After this lesson you will be able to connect to local and Atlas deployments, move between databases, get help on any command, and run JavaScript files against your data.

Connecting to a Deployment

mongosh is a separate download from the database server (it is also bundled with MongoDB Compass). With no arguments it connects to mongodb://localhost:27017.

bash
# Local server, default port mongosh # Explicit connection string, landing in the "shop" database mongosh "mongodb://localhost:27017/shop" # Atlas cluster (the +srv scheme resolves the cluster members via DNS) mongosh "mongodb+srv://cluster0.abcde.mongodb.net/shop" --username appuser # Useful flags mongosh --port 27018 --quiet # different port, no startup banner mongosh --eval "db.version()" # run one expression and exit mongosh --file seed.js # run a script and exit

When you pass --username without --password, the shell prompts for the password so it never lands in your terminal history. The prompt shows the current database (shop>); it shows test> if you did not specify one.

Moving Between Databases and Collections

javascript
show dbs // list databases that contain data use shop // switch to (or lazily create) a database db // print the current database name show collections // list collections in the current database db.getCollectionNames() // same list, returned as a JavaScript array db.stats() // sizes, document counts, index counts

A database or collection does not exist on disk until you write to it. use inventory followed by show dbs will not list inventory yet; db.items.insertOne({ sku: "A1" }) creates the collection and the database in one step.

The Shell Is a JavaScript REPL

Because mongosh is built on Node.js, variables, loops and functions work exactly as you expect:

javascript
const cheap = db.products.find({ price: { $lt: 20 } }).toArray(); cheap.length; // 3 for (let i = 1; i <= 3; i++) { db.logs.insertOne({ n: i, at: new Date() }); } function byTag(tag) { return db.products.find({ tags: tag }).sort({ price: 1 }); } byTag("office"); printjson(db.products.findOne()); // pretty-printed document

find() returns a cursor. At the prompt the shell prints the first 20 documents automatically; type it to page through the next batch. Inside scripts and functions nothing is printed automatically — call .toArray(), .forEach(printjson) or print() yourself.

For multi-line input, type .editor, paste a long pipeline, then press Ctrl+D to run it.

Getting Help Without Leaving the Shell

| Command | Shows | |---|---| | help | top-level shell commands | | db.help() | database methods (createCollection, runCommand, ...) | | db.products.help() | collection methods (find, updateMany, createIndex, ...) | | db.products.find().help() | cursor methods (sort, limit, explain, ...) | | db.version() | version of the server you are connected to | | db.runCommand({ ping: 1 }) | a raw database command; returns { ok: 1 } |

Scripts, Configuration and Startup Files

javascript
// seed.js — run with: mongosh "mongodb://localhost:27017/shop" --file seed.js db.products.deleteMany({}); db.products.insertMany([ { name: "Keyboard", price: 49.99, tags: ["office"] }, { name: "Monitor", price: 189.0, tags: ["office", "display"] }, ]); print(`Seeded ${db.products.countDocuments()} products`);

Inside an interactive session, load("seed.js") runs the same file. Shell settings persist between sessions through the config object:

javascript
config.set("displayBatchSize", 50) // print 50 documents per batch instead of 20 config.set("inspectDepth", 10) // show deeper nested documents config.get("historyLength")

A file named .mongoshrc.js in your home directory runs on every start; teams use it to define helper functions or a custom prompt.

Common Mistakes

  • Using use inside a script. use db is interactive shell syntax. In .js files write db = db.getSiblingDB("shop").
  • Expecting show dbs to list an empty database. Write a document first.
  • Running destructive commands on the wrong database. Check the prompt or run db before dropDatabase() or deleteMany({}).
Quick Quiz
Question 1 of 3

What does `use analytics` do if the `analytics` database does not exist yet?

Key Takeaways

  • mongosh connects with a connection string; mongodb+srv:// is the form used for Atlas clusters.
  • show dbs, use, show collections and db navigate the deployment; databases are created lazily on first write.
  • The shell is a full JavaScript REPL: variables, loops, functions and printjson() all work.
  • help, db.help() and db.<collection>.help() document every available method.
  • Automate with --eval, --file, load() and a .mongoshrc.js startup file.

Next lesson: Databases, Collections and Documents — how MongoDB organizes data and the rules that govern document structure.

mongosh Basics: Working in the MongoDB Shell - MongoDB | CodeYourCraft | CodeYourCraft