How to Use mongosh: MongoDB Shell Basics and Examples
Use
mongosh to start the MongoDB shell, which lets you connect to your database and run commands interactively. Simply open your terminal and type mongosh to connect to the default local MongoDB server or specify a connection string to connect remotely.Syntax
The basic syntax to start the MongoDB shell is:
mongosh: Connects to the local MongoDB server on default port 27017.mongosh <connection-string>: Connects to a remote or specific MongoDB instance using a connection string.- Inside the shell, you can run commands like
show dbsto list databases ordb.collection.find()to query data.
bash
mongosh
mongosh "mongodb+srv://username:password@cluster0.mongodb.net/myDatabase"Example
This example shows how to start mongosh, list databases, switch to a database, and query a collection.
mongodb
mongosh > show dbs > use test > db.users.find()
Output
test 0.000GB
admin 0.000GB
local 0.000GB
switched to db test
[ { _id: ObjectId("..."), name: "Alice", age: 25 }, { _id: ObjectId("..."), name: "Bob", age: 30 } ]
Common Pitfalls
Common mistakes when using mongosh include:
- Not having MongoDB server running before starting
mongosh, which causes connection errors. - Using the old
mongoshell command instead ofmongosh, which is deprecated. - Incorrect connection strings causing authentication failures.
- Forgetting to switch to the correct database with
use <dbname>before running queries.
bash
Wrong: mongo Right: mongosh Wrong: mongosh "mongodb://wrongUser:wrongPass@localhost:27017" Right: mongosh "mongodb://correctUser:correctPass@localhost:27017"
Quick Reference
| Command | Description |
|---|---|
| mongosh | Start MongoDB shell and connect to local server |
| mongosh | Connect to remote MongoDB server |
| show dbs | List all databases |
| use | Switch to a specific database |
| db.collection.find() | Query documents in a collection |
| exit | Exit the shell |
Key Takeaways
Start mongosh by typing
mongosh in your terminal to connect to MongoDB.Use
mongosh <connection-string> to connect to remote databases securely.Always ensure your MongoDB server is running before starting mongosh.
Switch to the correct database with
use <dbname> before running queries.Avoid using the deprecated
mongo shell; use mongosh instead.