MongoDB Cheatsheet
A User-friendly guide to MongoDB operations. Learn basic CRUD operations, aggregation, indexing, and more.
Basic Operations
Database Operations
Basic database management commands.
// Show all databases
show dbs
// Create/Switch database
use <database_name>
// Show current database
db
// Drop database
db.dropDatabase()
// Show collections
show collections
// Create collection
db.createCollection("users")
// Drop collection
db.users.drop()
Insert Operations
Adding documents to collections.
// Insert one document
db.users.insertOne({
name: "Alex",
email: "alex@example.com",
age: 28
})
// Insert multiple documents
db.users.insertMany([
{ name: "Emma", age: 25 },
{ name: "Michael", age: 30 }
])
// Insert with nested documents
db.users.insertOne({
name: "Sarah",
contact: {
email: "sarah@example.com",
phone: "123-456-7890"
},
interests: ["coding", "music"]
})
Query Operations
Basic Queries
Common query operations.
// Find all documents
db.users.find()
// Find with condition
db.users.find({ age: 25 })
// Find one document
db.users.findOne({ name: "Alex" })
// Pretty print results
db.users.find().pretty()
// Count documents
db.users.countDocuments()
// Distinct values
db.users.distinct("age")
// Query comparison
db.users.find({
age: { $gt: 25 }, // Greater than
salary: { $lt: 50000 }, // Less than
status: { $ne: "inactive" }, // Not equal
role: { $in: ["admin", "user"] } // In array
})
Query Operators
MongoDB query operators.
// Comparison operators
$eq // Equal
$ne // Not equal
$gt // Greater than
$gte // Greater than or equal
$lt // Less than
$lte // Less than or equal
$in // In array
$nin // Not in array
// Logical operators
$and: [{ age: { $gt: 25 }}, { status: "active" }]
$or: [{ age: 25 }, { age: 30 }]
$not: { age: 25 }
$nor: [{ age: 25 }, { age: 30 }]
// Element operators
$exists: true // Field exists
$type: "string" // Field type
// Example queries
db.users.find({
age: { $gte: 25, $lte: 50 },
status: { $exists: true },
"address.city": "New York"
})
Update Operations
Update Documents
Modifying existing documents.
// Update one document
db.users.updateOne(
{ name: "Alex" },
{ $set: { age: 29 } }
)
// Update multiple documents
db.users.updateMany(
{ status: "inactive" },
{ $set: { status: "active" } }
)
// Replace document
db.users.replaceOne(
{ name: "Alex" },
{ name: "Alexander", age: 29 }
)
// Update operators
$set // Set field value
$unset // Remove field
$inc // Increment field
$mul // Multiply field
$rename // Rename field
$min // Update if less than
$max // Update if greater than
// Array updates
$push // Add to array
$pop // Remove from array
$pull // Remove matching elements
$addToSet // Add unique to array
Array Updates
Working with array fields.
// Push to array
db.users.updateOne(
{ name: "Alex" },
{ $push: { interests: "sports" } }
)
// Push multiple values
db.users.updateOne(
{ name: "Alex" },
{
$push: {
interests: {
$each: ["reading", "travel"]
}
}
}
)
// Remove from array
db.users.updateOne(
{ name: "Alex" },
{ $pull: { interests: "sports" } }
)
// Add unique values
db.users.updateOne(
{ name: "Alex" },
{ $addToSet: { interests: "coding" } }
)
Delete Operations
Delete Documents
Removing documents from collections.
// Delete one document
db.users.deleteOne({ name: "Alex" })
// Delete multiple documents
db.users.deleteMany({ status: "inactive" })
// Delete all documents
db.users.deleteMany({})
// Delete with complex conditions
db.users.deleteMany({
$or: [
{ status: "inactive" },
{ lastLogin: { $lt: new Date('2023-01-01') } }
]
})
Aggregation
Aggregation Pipeline
Data aggregation operations.
// Basic aggregation
db.users.aggregate([
{ $match: { age: { $gt: 25 } } },
{ $group: { _id: "$status", count: { $sum: 1 } } }
])
// Multiple stages
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: {
_id: "$userId",
totalSpent: { $sum: "$amount" },
orderCount: { $sum: 1 }
}
},
{ $sort: { totalSpent: -1 } },
{ $limit: 5 }
])
// Common aggregation operators
$match // Filter documents
$group // Group documents
$sort // Sort documents
$limit // Limit results
$skip // Skip results
$project // Shape output
$unwind // Deconstruct array
$lookup // Join collections
Group Operations
Common grouping operations.
// Group by field
db.sales.aggregate([
{
$group: {
_id: "$category",
total: { $sum: "$amount" },
count: { $sum: 1 },
avg: { $avg: "$amount" },
max: { $max: "$amount" },
min: { $min: "$amount" }
}
}
])
// Multiple grouping
db.sales.aggregate([
{
$group: {
_id: {
category: "$category",
year: { $year: "$date" }
},
total: { $sum: "$amount" }
}
}
])
Indexes
Index Operations
Managing indexes for better performance.
// Create index
db.users.createIndex({ email: 1 })
// Create compound index
db.users.createIndex({
email: 1,
username: 1
})
// Create unique index
db.users.createIndex(
{ email: 1 },
{ unique: true }
)
// Text index
db.articles.createIndex(
{ title: "text", content: "text" }
)
// Show indexes
db.users.getIndexes()
// Drop index
db.users.dropIndex("email_1")
// Drop all indexes
db.users.dropIndexes()
Index Types
Different types of indexes.
// Single field index
db.users.createIndex({ age: 1 })
// Compound index
db.users.createIndex({ age: 1, name: 1 })
// Multikey index (arrays)
db.users.createIndex({ tags: 1 })
// Geospatial index
db.places.createIndex({ location: "2dsphere" })
// Hashed index
db.users.createIndex({ _id: "hashed" })
// Partial index
db.users.createIndex(
{ email: 1 },
{ partialFilterExpression: { age: { $gt: 18 } } }
)