First Shell Commands
Database Operations
Creating and Switching Databases
## Create/Switch to a new database
use labexDatabase
## Check current database
db
Listing Databases
## Show all databases
show dbs
Collection Management
Creating Collections
## Create a new collection
db.createCollection("users")
## Insert document into collection
db.users.insertOne({
name: "John Doe",
age: 30,
email: "[email protected]"
})
CRUD Operations
graph TD
A[CRUD Operations] --> B[Create]
A --> C[Read]
A --> D[Update]
A --> E[Delete]
Insert Operations
## Insert single document
db.users.insertOne({
username: "alice",
role: "developer"
})
## Insert multiple documents
db.users.insertMany([
{username: "bob", role: "admin"},
{username: "charlie", role: "user"}
])
Query Operations
## Find all documents
db.users.find()
## Find specific document
db.users.findOne({username: "alice"})
## Find with conditions
db.users.find({role: "developer"})
Query Operators
Operator |
Description |
Example |
$eq |
Equal to |
{age: {$eq: 30}} |
$gt |
Greater than |
{age: {$gt: 25}} |
$lt |
Less than |
{age: {$lt: 40}} |
$and |
Logical AND |
{and: [{age: {gt: 25}}, {role: "developer"}]} |
Update and Delete
Update Documents
## Update single document
db.users.updateOne(
{username: "alice"},
{$set: {role: "senior developer"}}
)
## Update multiple documents
db.users.updateMany(
{role: "developer"},
{$inc: {experience: 1}}
)
Delete Documents
## Delete single document
db.users.deleteOne({username: "charlie"})
## Delete multiple documents
db.users.deleteMany({role: "user"})
Advanced Shell Commands
Aggregation
db.users.aggregate([
{$group: {_id: "$role", total: {$sum: 1}}}
])
Shell Configuration in LabEx
When using LabEx platform, the MongoDB shell provides an intuitive environment for learning and practicing database operations, with pre-configured settings for seamless interaction.
Best Practices
- Always use filters in queries
- Limit result sets
- Create appropriate indexes
- Use projection to return specific fields