← Back to MongoDB Course | Chapter 1: Introduction | Lesson 7 of 7

mongosh basics

mongosh is the interactive shell for running MongoDB commands and JavaScript.

In this page:

  1. mongosh basics
Syntax
javascript
mongosh
show dbs
use database_name
show collections
db.collection_name.find()

mongosh basics

Start it with mongosh and it connects to localhost by default. Helpers include show dbs, use name, show collections and db.stats().

It is a JavaScript shell, so you can use variables, loops and functions, and press Tab for autocomplete.

Type exit to leave.

Note:
  • use dbname switches to a database even if it does not exist yet.
  • It is created on first write.

Example: mongosh basics

bash
test> show dbs
admin   40.00 KiB
config  60.00 KiB
local   72.00 KiB
test> use shop
switched to db shop
shop> db.products.insertOne({ name: "Pen", price: 3 })
{ acknowledged: true, insertedId: ObjectId('65a1b2c3d4e5f60718293a4c') }
shop> show collections
products
shop> exit

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Forgetting to run use before working
  2. Confusing db (current database) with a collection
  3. Expecting semicolons to be required
Chapter Summary
  • mongosh is a JavaScript shell
  • show dbs, use, show collections
  • db refers to the current database
  • Databases are created on first write
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.