mongosh basics
mongosh is the interactive shell for running MongoDB commands and JavaScript.
In this page:
Syntax
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
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
- Forgetting to run use before working
- Confusing db (current database) with a collection
- 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: