MongoDB Shell Basics
What is MongoDB Shell?
MongoDB Shell, also known as mongosh
, is an interactive command-line interface for MongoDB databases. It provides a powerful environment for administrators and developers to interact directly with MongoDB, execute queries, manage databases, and perform administrative tasks.
Installation on Ubuntu 22.04
To install MongoDB Shell on Ubuntu, follow these steps:
## Import MongoDB public GPG key
wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -
## Add MongoDB repository
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org.list
## Update package lists
sudo apt-get update
## Install MongoDB Shell
sudo apt-get install -y mongodb-mongosh
Basic Shell Commands
Here's a markdown table of essential MongoDB Shell commands:
Command |
Description |
Example |
show dbs |
List all databases |
> show dbs |
use <database> |
Switch to a specific database |
> use myDatabase |
db |
Show current database |
> db |
show collections |
List collections in current database |
> show collections |
Connection Workflow
graph TD
A[Start] --> B[Launch MongoDB Shell]
B --> C{Connection Successful?}
C -->|Yes| D[Select/Create Database]
C -->|No| E[Troubleshoot Connection]
D --> F[Perform Operations]
Basic Query Operations
// Insert a document
db.users.insertOne({
name: "John Doe",
age: 30,
email: "[email protected]"
})
// Find documents
db.users.find()
// Update a document
db.users.updateOne(
{ name: "John Doe" },
{ $set: { age: 31 } }
)
// Delete a document
db.users.deleteOne({ name: "John Doe" })
Shell Configuration
You can customize your MongoDB Shell experience by configuring settings in the .mongorc.js
file located in your home directory.
Best Practices
- Always use authentication in production environments
- Close connections when not in use
- Use indexes for better query performance
- Regularly update MongoDB Shell
LabEx Recommendation
For hands-on practice, LabEx offers interactive MongoDB Shell learning environments that help developers master database management skills efficiently.