Bird
Raised Fist0
MongoDBquery~10 mins

MongoDB Shell (mongosh) basics - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - MongoDB Shell (mongosh) basics
Start mongosh
Connect to MongoDB
Show databases
Select database
Show collections
Run queries or commands
Exit mongosh
This flow shows how you start the MongoDB shell, connect to the server, explore databases and collections, run commands, and then exit.
Execution Sample
MongoDB
mongosh
show dbs
db = db.getSiblingDB('testdb')
db.createCollection('users')
db.users.insertOne({name: 'Alice'})
db.users.find()
This code starts the shell, lists databases, switches to 'testdb', creates a collection, inserts a document, and finds documents.
Execution Table
StepCommandActionResult
1mongoshStart MongoDB shellConnected to MongoDB server
2show dbsList all databases[admin, local, testdb]
3db = db.getSiblingDB('testdb')Switch to 'testdb' databaseSwitched to 'testdb'
4db.createCollection('users')Create 'users' collectionCollection 'users' created
5db.users.insertOne({name: 'Alice'})Insert document into 'users'Inserted 1 document with _id
6db.users.find()Find all documents in 'users'[{_id: ObjectId(...), name: 'Alice'}]
7exitExit mongoshShell closed
💡 User exits the shell with 'exit' command
Variable Tracker
VariableStartAfter Step 3After Step 4After Step 5After Step 6Final
dbdefaulttestdbtestdbtestdbtestdbtestdb
users collectionnonenonecreatedcreated with 1 documentcreated with 1 documentcreated with 1 document
Key Moments - 3 Insights
Why do we use db.getSiblingDB('testdb') instead of just db?
Because 'db' starts as the default database (usually 'test'), getSiblingDB switches to the named database without restarting the shell. See execution_table step 3.
What does insertOne return and why is _id important?
insertOne returns an object with the inserted document's _id, which uniquely identifies the document. This is shown in execution_table step 5.
Why does find() return an array with ObjectId?
Because find() returns documents matching the query; each document has a unique _id of type ObjectId. See execution_table step 6.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'db' after step 3?
A'testdb'
B'admin'
C'local'
D'default'
💡 Hint
Check the variable_tracker table under 'db' after Step 3
At which step is the 'users' collection created?
AStep 2
BStep 4
CStep 3
DStep 5
💡 Hint
Look at the 'Action' column in execution_table for collection creation
If you run db.users.find() before inserting any documents, what would the result be?
AA document with _id
BAn error
CAn empty array []
DThe collection is deleted
💡 Hint
Think about what find() returns when no documents exist in the collection
Concept Snapshot
MongoDB Shell (mongosh) basics:
- Start shell with 'mongosh'
- Use 'show dbs' to list databases
- Switch DB with db.getSiblingDB('name')
- Create collections with createCollection()
- Insert documents with insertOne()
- Query documents with find()
- Exit shell with 'exit'
Full Transcript
This lesson shows how to use the MongoDB shell called mongosh. First, you start the shell by typing 'mongosh'. Then, you can list all databases using 'show dbs'. To work with a specific database, use db.getSiblingDB('databaseName'). You can create a collection with createCollection('collectionName'). To add data, use insertOne() with a document. To see data, use find(). Finally, exit the shell by typing 'exit'. Each step changes the state of the shell and database, which we tracked in the tables.

Practice

(1/5)
1. What command in mongosh lists all the databases available on the server?
easy
A. show dbs
B. list databases
C. show collections
D. dbs list

Solution

  1. Step 1: Understand the command purpose

    The question asks for the command that lists all databases in mongosh.
  2. Step 2: Recall mongosh commands

    show dbs is the correct command to list databases. Other options are incorrect or do not exist.
  3. Final Answer:

    show dbs -> Option A
  4. Quick Check:

    List databases = show dbs [OK]
Hint: Use 'show dbs' to list all databases quickly [OK]
Common Mistakes:
  • Confusing 'show collections' with listing databases
  • Using non-existent commands like 'list databases'
  • Trying 'dbs list' which is invalid
2. Which of the following is the correct syntax to switch to a database named shop in mongosh?
easy
A. switch shop
B. use shop
C. db switch shop
D. change db shop

Solution

  1. Step 1: Identify the command to change database

    In mongosh, the command to switch databases is use followed by the database name.
  2. Step 2: Match the correct syntax

    use shop correctly switches to the 'shop' database. Other options are invalid commands.
  3. Final Answer:

    use shop -> Option B
  4. Quick Check:

    Switch database = use [OK]
Hint: Remember: 'use' changes the current database [OK]
Common Mistakes:
  • Using 'switch' instead of 'use'
  • Adding extra words like 'db' or 'change'
  • Typing commands that don't exist in mongosh
3. Given the following commands in mongosh:
use testdb
db.products.insertOne({name: 'Pen', price: 1.5})
db.products.find({name: 'Pen'}).toArray()

What will be the output of the find() command?
medium
A. [{ _id: ObjectId("...") , name: 'Pen', price: 1.5 }]
B. null
C. SyntaxError
D. []

Solution

  1. Step 1: Insert a document into 'products' collection

    The insertOne() command adds a document with name 'Pen' and price 1.5 to the 'products' collection.
  2. Step 2: Query the collection for documents with name 'Pen'

    The find() command searches for documents matching {name: 'Pen'}. Since we inserted one, it returns an array with that document including an auto-generated _id.
  3. Final Answer:

    [{ _id: ObjectId("...") , name: 'Pen', price: 1.5 }] -> Option A
  4. Quick Check:

    Inserted doc found = array with document [OK]
Hint: Inserted documents appear in find results as arrays [OK]
Common Mistakes:
  • Expecting find() to return null if document exists
  • Confusing syntax causing errors
  • Thinking find() returns a single object, not an array
4. You run this command in mongosh:
db.users.insertOne({name: 'Alice', age: 30})

But get an error: ReferenceError: db is not defined. What is the most likely cause?
medium
A. The syntax of the insertOne command is incorrect
B. The insertOne method does not exist
C. You forgot to switch to a database using use command
D. MongoDB server is not running

Solution

  1. Step 1: Understand the error message

    ReferenceError: db is not defined means the shell does not know what db is.
  2. Step 2: Identify cause in mongosh context

    This usually happens if you have not selected a database with use. Without a current database, db is undefined.
  3. Final Answer:

    You forgot to switch to a database using use command -> Option C
  4. Quick Check:

    db undefined = forgot 'use' [OK]
Hint: Always run 'use dbname' before using db commands [OK]
Common Mistakes:
  • Assuming insertOne method is missing
  • Thinking syntax is wrong when it is correct
  • Ignoring the need to start MongoDB server
5. You want to list all collections in the current database and then insert a document into a collection named orders. Which sequence of commands in mongosh is correct?
hard
A. show collections use orders db.insertOne({item: 'Book', qty: 3})
B. show dbs db.orders.insertOne({item: 'Book', qty: 3})
C. use orders show collections db.insertOne({item: 'Book', qty: 3})
D. show collections db.orders.insertOne({item: 'Book', qty: 3})

Solution

  1. Step 1: List collections in current database

    show collections lists all collections in the current database. This is the first correct step.
  2. Step 2: Insert document into 'orders' collection

    Use db.orders.insertOne(...) to insert a document into the 'orders' collection. This is the correct syntax.
  3. Final Answer:

    show collections db.orders.insertOne({item: 'Book', qty: 3}) -> Option D
  4. Quick Check:

    List collections then insert = show collections db.orders.insertOne({item: 'Book', qty: 3}) [OK]
Hint: Use 'db.collection.insertOne()' after 'show collections' [OK]
Common Mistakes:
  • Trying to 'use' a collection as a database
  • Calling insertOne directly on db without collection
  • Listing databases instead of collections