- Basic CRUD Operations Create (Insert) javascript // Insert one document db.collection.insertOne({name: "John", age: 30, city: "New York"})
// Insert multiple documents
db.collection.insertMany([
{name: "Alice", age: 25, city: "London"},
{name: "Bob", age: 35, city: "Paris"}
])
Read (Find)
javascript
// Find all documents
db.collection.find()
// Find with condition
db.collection.find({age: 30})
// Find one document
db.collection.findOne({name: "John"})
// Pretty print
db.collection.find().pretty()
Update
javascript
// Update one document
db.collection.updateOne(
{name: "John"},
{$set: {age: 31}}
)
// Update multiple documents
db.collection.updateMany(
{city: "London"},
{$set: {country: "UK"}}
)
// Replace entire document
db.collection.replaceOne(
{name: "John"},
{name: "John", age: 32, city: "Boston"}
)
Delete
javascript
// Delete one document
db.collection.deleteOne({name: "John"})
// Delete multiple documents
db.collection.deleteMany({age: {$lt: 25}})
- Query Operators Comparison Operators javascript // Equal db.collection.find({age: 30})
// Not equal
db.collection.find({age: {$ne: 30}})
// Greater than
db.collection.find({age: {$gt: 30}})
// Greater than or equal
db.collection.find({age: {$gte: 30}})
// Less than
db.collection.find({age: {$lt: 30}})
// Less than or equal
db.collection.find({age: {$lte: 30}})
// In array of values
db.collection.find({age: {$in: [25, 30, 35]}})
// Not in array
db.collection.find({age: {$nin: [25, 30, 35]}})
Logical Operators
javascript
// AND (implicit)
db.collection.find({age: 30, city: "London"})
// AND (explicit)
db.collection.find({$and: [{age: 30}, {city: "London"}]})
// OR
db.collection.find({$or: [{age: 30}, {city: "London"}]})
// NOT
db.collection.find({age: {$not: {$gt: 30}}})
// NOR
db.collection.find({$nor: [{age: 30}, {city: "London"}]})
Element Operators
javascript
// Field exists
db.collection.find({email: {$exists: true}})
// Field doesn't exist
db.collection.find({email: {$exists: false}})
// Type check
db.collection.find({age: {$type: "number"}})
db.collection.find({age: {$type: 16}}) // 16 = 32-bit integer
Array Operators
javascript
// All elements match
db.collection.find({tags: {$all: ["red", "blue"]}})
// Array size
db.collection.find({tags: {$size: 3}})
// Element match (for arrays of objects)
db.collection.find({
scores: {$elemMatch: {score: {$gt: 80}, subject: "math"}}
})
- Regular Expressions javascript // Case-sensitive regex db.collection.find({name: /^J/})
// Case-insensitive regex
db.collection.find({name: /john/i})
// Using $regex operator
db.collection.find({name: {$regex: "john", $options: "i"}})
// Complex patterns
db.collection.find({email: {$regex: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/}})
- Projection javascript // Include specific fields db.collection.find({}, {name: 1, age: 1})
// Exclude specific fields
db.collection.find({}, {password: 0, ssn: 0})
// Include field in nested document
db.collection.find({}, {"address.city": 1})
// Array element projection
db.collection.find({}, {tags: {$slice: 2}}) // First 2 elements
db.collection.find({}, {tags: {$slice: -2}}) // Last 2 elements
db.collection.find({}, {tags: {$slice: [1, 3]}}) // Skip 1, take 3
- Sorting and Limiting javascript // Sort ascending db.collection.find().sort({age: 1})
// Sort descending
db.collection.find().sort({age: -1})
// Multiple sort fields
db.collection.find().sort({age: -1, name: 1})
// Limit results
db.collection.find().limit(5)
// Skip documents
db.collection.find().skip(10)
// Pagination
db.collection.find().skip(20).limit(10)
- Aggregation Framework Basic Pipeline javascript db.collection.aggregate([ {$match: {age: {$gte: 25}}}, {$group: {_id: "$city", count: {$sum: 1}}}, {$sort: {count: -1}} ]) Common Pipeline Stages javascript // $match - Filter documents {$match: {status: "active"}}
// $group - Group documents
{$group: {
_id: "$category",
total: {$sum: "$amount"},
avg: {$avg: "$amount"},
count: {$sum: 1}
}}
// $project - Reshape documents
{$project: {
name: 1,
age: 1,
fullName: {$concat: ["$firstName", " ", "$lastName"]},
isAdult: {$gte: ["$age", 18]}
}}
// $sort - Sort documents
{$sort: {age: -1, name: 1}}
// $limit - Limit results
{$limit: 10}
// $skip - Skip documents
{$skip: 5}
// $unwind - Deconstruct arrays
{$unwind: "$tags"}
// $lookup - Join collections
{$lookup: {
from: "orders",
localField: "_id",
foreignField: "userId",
as: "userOrders"
}}
Advanced Aggregation Examples
javascript
// Complex grouping with multiple operations
db.sales.aggregate([
{$match: {date: {$gte: new Date("2023-01-01")}}},
{$group: {
_id: {
year: {$year: "$date"},
month: {$month: "$date"},
product: "$product"
},
totalSales: {$sum: "$amount"},
averageSale: {$avg: "$amount"},
minSale: {$min: "$amount"},
maxSale: {$max: "$amount"},
salesCount: {$sum: 1}
}},
{$sort: {"_id.year": 1, "_id.month": 1}},
{$project: {
_id: 0,
year: "$_id.year",
month: "$_id.month",
product: "$_id.product",
totalSales: 1,
averageSale: {$round: ["$averageSale", 2]},
salesCount: 1
}}
])
// Lookup with pipeline
db.users.aggregate([
{$lookup: {
from: "orders",
let: {userId: "$_id"},
pipeline: [
{$match: {$expr: {$eq: ["$userId", "$$userId"]}}},
{$match: {status: "completed"}},
{$group: {_id: null, total: {$sum: "$amount"}}}
],
as: "completedOrders"
}}
])
- Indexing Creating Indexes javascript // Single field index db.collection.createIndex({name: 1})
// Compound index
db.collection.createIndex({name: 1, age: -1})
// Text index
db.collection.createIndex({title: "text", content: "text"})
// Geospatial index
db.collection.createIndex({location: "2dsphere"})
// Partial index
db.collection.createIndex(
{email: 1},
{partialFilterExpression: {email: {$exists: true}}}
)
// TTL index (auto-expire documents)
db.collection.createIndex(
{createdAt: 1},
{expireAfterSeconds: 3600}
)
Index Management
javascript
// List indexes
db.collection.getIndexes()
// Drop index
db.collection.dropIndex({name: 1})
db.collection.dropIndex("name_1")
// Drop all indexes
db.collection.dropIndexes()
// Explain query plan
db.collection.find({name: "John"}).explain("executionStats")
- Advanced Update Operations Update Operators javascript // $set - Set field value db.collection.updateOne({_id: 1}, {$set: {age: 31}})
// $unset - Remove field
db.collection.updateOne({_id: 1}, {$unset: {age: ""}})
// $inc - Increment field
db.collection.updateOne({_id: 1}, {$inc: {age: 1, views: 10}})
// $mul - Multiply field
db.collection.updateOne({_id: 1}, {$mul: {price: 1.1}})
// $min/$max - Update if new value is min/max
db.collection.updateOne({_id: 1}, {$min: {lowScore: 50}})
db.collection.updateOne({_id: 1}, {$max: {highScore: 100}})
// $currentDate - Set to current date
db.collection.updateOne({_id: 1}, {$currentDate: {lastModified: true}})
Array Update Operators
javascript
// $push - Add element to array
db.collection.updateOne({_id: 1}, {$push: {tags: "new-tag"}})
// $push with $each (multiple elements)
db.collection.updateOne({_id: 1}, {$push: {tags: {$each: ["tag1", "tag2"]}}})
// $addToSet - Add unique element
db.collection.updateOne({_id: 1}, {$addToSet: {tags: "unique-tag"}})
// $pop - Remove first or last element
db.collection.updateOne({_id: 1}, {$pop: {tags: 1}}) // Remove last
db.collection.updateOne({_id: 1}, {$pop: {tags: -1}}) // Remove first
// $pull - Remove elements matching condition
db.collection.updateOne({_id: 1}, {$pull: {tags: "old-tag"}})
db.collection.updateOne({_id: 1}, {$pull: {scores: {$lt: 50}}})
// $pullAll - Remove multiple specific values
db.collection.updateOne({_id: 1}, {$pullAll: {tags: ["tag1", "tag2"]}})
// Update array element by position
db.collection.updateOne({_id: 1}, {$set: {"tags.0": "first-tag"}})
// Update array element by condition ($ positional operator)
db.collection.updateOne(
{"scores.score": 85},
{$set: {"scores.$.grade": "B"}}
)
// Update all array elements ($[] positional operator)
db.collection.updateOne(
{_id: 1},
{$inc: {"scores.$[].attempts": 1}}
)
// Update filtered array elements ($[identifier] positional operator)
db.collection.updateOne(
{_id: 1},
{$set: {"scores.$[elem].grade": "A"}},
{arrayFilters: [{"elem.score": {$gte: 90}}]}
)
- Text Search javascript // Create text index db.articles.createIndex({title: "text", content: "text"})
// Basic text search
db.articles.find({$text: {$search: "mongodb database"}})
// Search with phrases
db.articles.find({$text: {$search: "\"exact phrase\""}})
// Exclude terms
db.articles.find({$text: {$search: "mongodb -sql"}})
// Text search with score
db.articles.find(
{$text: {$search: "mongodb"}},
{score: {$meta: "textScore"}}
).sort({score: {$meta: "textScore"}})
- Geospatial Queries javascript // Create 2dsphere index db.places.createIndex({location: "2dsphere"})
// Find near point
db.places.find({
location: {
$near: {
$geometry: {type: "Point", coordinates: [-73.9857, 40.7484]},
$maxDistance: 1000
}
}
})
// Find within polygon
db.places.find({
location: {
$geoWithin: {
$geometry: {
type: "Polygon",
coordinates: [[
[-74, 40.5],
[-74, 41],
[-73, 41],
[-73, 40.5],
[-74, 40.5]
]]
}
}
}
})
- Advanced Aggregation Operators Conditional Operators javascript // $cond - Conditional expression {$project: { status: { $cond: { if: {$gte: ["$age", 18]}, then: "adult", else: "minor" } } }}
// $switch - Multiple conditions
{$project: {
grade: {
$switch: {
branches: [
{case: {$gte: ["$score", 90]}, then: "A"},
{case: {$gte: ["$score", 80]}, then: "B"},
{case: {$gte: ["$score", 70]}, then: "C"}
],
default: "F"
}
}
}}
Date Operators
javascript
// Extract date parts
{$project: {
year: {$year: "$createdAt"},
month: {$month: "$createdAt"},
dayOfWeek: {$dayOfWeek: "$createdAt"},
dayOfYear: {$dayOfYear: "$createdAt"}
}}
// Date arithmetic
{$project: {
futureDate: {$add: ["$createdAt", 7 * 24 * 60 * 60 * 1000]} // Add 7 days
}}
// Date formatting
{$project: {
formattedDate: {
$dateToString: {
format: "%Y-%m-%d %H:%M:%S",
date: "$createdAt"
}
}
}}
String Operators
javascript
// String manipulation
{$project: {
upperName: {$toUpper: "$name"},
lowerName: {$toLower: "$name"},
nameLength: {$strLenCP: "$name"},
initials: {$substr: ["$name", 0, 1]},
fullName: {$concat: ["$firstName", " ", "$lastName"]},
words: {$split: ["$name", " "]}
}}
// String search
{$match: {
$expr: {
$regexMatch: {
input: "$email",
regex: "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
}
}
}}
- Complex Aggregation Examples Data Analysis Pipeline javascript db.sales.aggregate([ // Stage 1: Filter recent sales {$match: { date: {$gte: new Date("2023-01-01")}, status: "completed" }},
// Stage 2: Add calculated fields
{$addFields: {
month: {$month: "$date"},
year: {$year: "$date"},
profit: {$subtract: ["$revenue", "$cost"]}
}},
// Stage 3: Group by product and month
{$group: {
_id: {
product: "$product",
year: "$year",
month: "$month"
},
totalRevenue: {$sum: "$revenue"},
totalProfit: {$sum: "$profit"},
avgOrderValue: {$avg: "$revenue"},
orderCount: {$sum: 1},
topCustomer: {$first: "$customer"}
}},
// Stage 4: Calculate profit margin
{$addFields: {
profitMargin: {
$multiply: [
{$divide: ["$totalProfit", "$totalRevenue"]},
100
]
}
}},
// Stage 5: Sort by profit margin
{$sort: {profitMargin: -1}},
// Stage 6: Group by product for summary
{$group: {
_id: "$_id.product",
monthlyData: {
$push: {
year: "$_id.year",
month: "$_id.month",
revenue: "$totalRevenue",
profit: "$totalProfit",
margin: "$profitMargin",
orders: "$orderCount"
}
},
totalRevenue: {$sum: "$totalRevenue"},
avgMargin: {$avg: "$profitMargin"}
}},
// Stage 7: Final projection
{$project: {
_id: 0,
product: "$_id",
totalRevenue: 1,
avgMargin: {$round: ["$avgMargin", 2]},
monthlyData: 1,
performance: {
$cond: {
if: {$gte: ["$avgMargin", 20]},
then: "excellent",
else: {
$cond: {
if: {$gte: ["$avgMargin", 10]},
then: "good",
else: "needs_improvement"
}
}
}
}
}}
])
- Performance Optimization Tips Query Optimization javascript // Use indexes effectively db.collection.find({status: "active", category: "electronics"}) // Create compound index: db.collection.createIndex({status: 1, category: 1})
// Use projection to limit data transfer
db.collection.find({status: "active"}, {name: 1, price: 1})
// Use hint to force index usage
db.collection.find({name: "John"}).hint({name: 1})
// Use explain to analyze query performance
db.collection.find({name: "John"}).explain("executionStats")
Aggregation Optimization
javascript
// Put $match as early as possible
db.collection.aggregate([
{$match: {status: "active"}}, // Filter first
{$lookup: {...}},
{$group: {...}}
])
// Use $project to reduce document size early
db.collection.aggregate([
{$match: {status: "active"}},
{$project: {name: 1, age: 1, city: 1}}, // Reduce data size
{$group: {...}}
])
This comprehensive guide covers MongoDB queries from basic CRUD operations to advanced aggregation pipelines and optimization techniques. Each section builds upon the previous ones, providing practical examples you can use in real applications.
Top comments (0)