โ† Back to Syllabus

๐Ÿ’ป mongosh Basics

Phase 1 ยท Topic 3 of 10 ยท ~1 hour ยท connect, show dbs, use db

What is mongosh?

mongosh (MongoDB Shell) is the official interactive command-line interface for MongoDB. Think of it as your direct conversation with the database โ€” you type commands, it responds with data.

SQL WorldMongoDB World
mysql CLImongosh
sqlcmd (SQL Server)mongosh
psql (PostgreSQL)mongosh
mongosh is a full JavaScript REPL. That means you can use variables, loops, functions โ€” real JavaScript โ€” right inside the shell. This is way more powerful than a typical SQL CLI.

Connecting to MongoDB

Default Local Connection

If MongoDB is running locally on the default port, just type:

mongosh

This is shorthand for:

mongosh "mongodb://localhost:27017"

Connection String Anatomy

mongodb://  localhost  :  27017  /  myDatabase
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€    โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€    โ”€โ”€โ”€โ”€โ”€     โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
protocol    host         port      database (optional)

Connect to a Specific Database Directly

// Connects and switches to "myShop" immediately
mongosh "mongodb://localhost:27017/myShop"

Connection with Authentication

// When your server requires a username/password
mongosh "mongodb://localhost:27017" --username [user] --password [pass]

// Or in the connection string
mongosh "mongodb://[user]:[pass]@localhost:27017/admin"
โœ… When connected, you'll see a prompt like:
test> or myShop> โ€” this shows which database you're currently using.

Essential Navigation Commands

These are the commands you'll use constantly. Here's the SQL equivalent for each:

show dbs โ€” List All Databases

test> show dbs

// Output:
// admin    40.00 KiB
// config  108.00 KiB
// local    40.00 KiB
MongoDBSQL Equivalent
show dbsSHOW DATABASES; (MySQL) or query sys.databases (SQL Server)
โš ๏ธ Note: A database won't appear in show dbs until it has at least one document in it. Creating a database with use alone isn't enough โ€” it's "lazy created."

use โ€” Switch to a Database

test> use myShop
// Output: switched to db myShop

myShop>

If the database doesn't exist yet, MongoDB doesn't complain โ€” it just creates it when you first insert data. No CREATE DATABASE needed.

MongoDBSQL Equivalent
use myShopUSE myShop; (MySQL) or USE [myShop]; (SQL Server)

db โ€” Show Current Database

myShop> db
// Output: myShop
MongoDBSQL Equivalent
dbSELECT DATABASE(); (MySQL) or SELECT DB_NAME(); (SQL Server)

show collections โ€” List Collections in Current DB

myShop> show collections

// Output:
// products
// orders
// customers
MongoDBSQL Equivalent
show collectionsSHOW TABLES; (MySQL) or query sys.tables (SQL Server)

Quick Data Commands (Preview)

You'll learn these in depth later, but here's a taste so you can experiment in the shell right now:

// Switch to a practice database
use practice

// Insert a document (creates the collection automatically)
db.users.insertOne({
  name: "Alex",
  age: 28,
  role: "developer"
})

// Find all documents in the collection
db.users.find()

// Find with a filter (like WHERE)
db.users.find({ role: "developer" })

// Count documents
db.users.countDocuments()

// Drop the collection when done experimenting
db.users.drop()

// Drop the entire database
db.dropDatabase()
Key insight: In MongoDB, you never need to "create" a database or collection upfront. Just use a database and insertOne() into a collection โ€” both are created automatically on first write. This is very different from SQL where you must CREATE DATABASE and CREATE TABLE first.

Helpful mongosh Features

Tab Completion

Type db. and press Tab โ€” mongosh will show you all available methods. Works for collection names too.

Command History

Press โ†‘ and โ†“ arrow keys to cycle through previous commands, just like any terminal.

Multi-line Input

mongosh automatically detects incomplete expressions. If you open a { and press Enter, it waits for the closing }:

myShop> db.users.insertOne({
...   name: "Sam",
...   age: 32
... })

Built-in Help

// General help
help

// Database-level help
db.help()

// Collection-level help
db.users.help()

.editor Mode

For longer commands, enter editor mode:

myShop> .editor
// Entering editor mode (Ctrl+D to finish, Ctrl+C to cancel)

db.products.insertMany([
  { name: "Laptop", price: 999, category: "electronics" },
  { name: "Mouse", price: 29, category: "electronics" },
  { name: "Desk", price: 250, category: "furniture" }
])

// Press Ctrl+D to execute

Clear the Screen

cls
// or
console.clear()

Exit mongosh

exit
// or
quit
// or press Ctrl+C twice

๐Ÿ“‹ mongosh Quick Reference

CommandWhat It DoesSQL Equivalent
mongoshConnect to local MongoDBOpen SQL CLI
show dbsList all databasesSHOW DATABASES
use myDbSwitch to / create databaseUSE myDb / CREATE DATABASE
dbShow current database nameSELECT DATABASE()
show collectionsList collections in current dbSHOW TABLES
db.col.find()Show all documentsSELECT * FROM col
db.col.insertOne({...})Insert one documentINSERT INTO col ...
db.col.countDocuments()Count documentsSELECT COUNT(*) FROM col
db.col.drop()Delete a collectionDROP TABLE col
db.dropDatabase()Delete current databaseDROP DATABASE

๐Ÿ‹๏ธ Try It Yourself

Open mongosh and complete these exercises:

Exercise 1: List all databases. How many do you see?

Exercise 2: Create a database called playground and insert this document into a notes collection:
{ title: "My first note", content: "Learning mongosh!", createdAt: new Date() }
Exercise 3: Run show dbs โ€” does playground appear now?

Exercise 4: Run db.notes.find() to see your document. Notice the _id field that MongoDB added automatically.

Exercise 5: Clean up โ€” drop the playground database with db.dropDatabase().

๐Ÿง  Quick Check

Test yourself:

1. What command lists all databases in MongoDB?

2. What happens when you run use newDb and newDb doesn't exist?

3. When does a new database first appear in show dbs?

4. What language does mongosh use under the hood?