MongoDB shell commands and aggregation pipeline examples
List all databases
show dbs
Switch to a database
use myapp
Delete current database
db.dropDatabase()
Show database statistics
db.stats()
List all collections
show collections
Create a new collection
db.createCollection("users")
Delete a collection
db.users.drop()
Show collection statistics
db.users.stats()
Insert a single document
db.users.insertOne({name: "John", age: 30})
Insert multiple documents
db.users.insertMany([{name: "John"}, {name: "Jane"}])
Query documents
db.users.find({age: {$gt: 25}})
Find first matching document
db.users.findOne({name: "John"})
Update first matching document
db.users.updateOne({name: "John"}, {$set: {age: 31}})
Update all matching documents
db.users.updateMany({age: {$lt: 30}}, {$inc: {age: 1}})
Delete first matching document
db.users.deleteOne({name: "John"})
Delete all matching documents
db.users.deleteMany({age: {$lt: 18}})
Equal to
db.users.find({age: {$eq: 30}})
Greater than, greater than or equal
db.users.find({age: {$gt: 25, $lte: 50}})
Less than, less than or equal
db.users.find({age: {$lt: 30}})
In array, not in array
db.users.find({age: {$in: [25, 30, 35]}})
Logical operators
db.users.find({$and: [{age: {$gt: 25}}, {city: "NYC"}]})
Regular expression
db.users.find({name: {$regex: "^J"}})
Filter documents
db.users.aggregate([{$match: {age: {$gt: 25}}}])
Group documents
db.users.aggregate([{$group: {_id: "$city", count: {$sum: 1}}}])
Sort documents
db.users.aggregate([{$sort: {age: -1}}])
Limit and skip documents
db.users.aggregate([{$skip: 10}, {$limit: 5}])
Select fields
db.users.aggregate([{$project: {name: 1, age: 1, _id: 0}}])
Join collections
db.orders.aggregate([{$lookup: {from: "users", localField: "userId", foreignField: "_id", as: "user"}}])
Create an index
db.users.createIndex({email: 1})
Create unique index
db.users.createIndex({email: 1}, {unique: true})
List all indexes
db.users.getIndexes()
Remove an index
db.users.dropIndex("email_1")
Create, Read, Update, Delete operations
// Create
db.users.insertOne({
name: "John Doe",
email: "[email protected]",
age: 30,
created_at: new Date()
})
// Read
db.users.find({age: {$gte: 25}}).sort({name: 1})
// Update
db.users.updateOne(
{email: "[email protected]"},
{$set: {age: 31, updated_at: new Date()}}
)
// Delete
db.users.deleteOne({email: "[email protected]"})
Multi-stage aggregation pipeline
db.orders.aggregate([
// Match orders from last month
{
$match: {
created_at: {
$gte: new Date("2024-01-01"),
$lt: new Date("2024-02-01")
}
}
},
// Lookup user information
{
$lookup: {
from: "users",
localField: "user_id",
foreignField: "_id",
as: "user"
}
},
// Group by user and calculate totals
{
$group: {
_id: "$user_id",
total_orders: {$sum: 1},
total_amount: {$sum: "$amount"},
user_name: {$first: "$user.name"}
}
},
// Sort by total amount
{
$sort: {total_amount: -1}
}
])
Full-text search operations
// Create text index
db.products.createIndex({name: "text", description: "text"})
// Search for products
db.products.find({
$text: {
$search: "laptop computer",
$caseSensitive: false
}
}, {
score: {$meta: "textScore"}
}).sort({score: {$meta: "textScore"}})
Schema validation for collections
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "email", "age"],
properties: {
name: {
bsonType: "string",
minLength: 2
},
email: {
bsonType: "string",
pattern: "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
},
age: {
bsonType: "int",
minimum: 0,
maximum: 120
}
}
}
}
})
Always use indexes for frequently queried fields
Use explain()
to analyze query performance
Embed related data when it's small and doesn't change often
Use $lookup
for large or frequently changing related data
Implement data validation using schema validation