1 / 8
🔍 MongoDB Advanced Queries
🎯 Darsning Maqsadi
MongoDB'da murakkab so'rovlar, aggregation pipeline va optimizatsiya texnikalarini o'rganish.
📋 Dars Rejasi
- Query operators
- Aggregation pipeline
- Indexing
- Performance optimization
- Real-world examples
🔍 Query Operators
📊 Comparison Operators
// Taqqoslash operatorlari
db.users.find({ age: { $gte: 18, $lte: 65 } })
db.users.find({ age: { $gt: 25 } })
db.users.find({ age: { $lt: 30 } })
db.users.find({ age: { $ne: 25 } })
db.users.find({ age: { $in: [25, 30, 35] } })
db.users.find({ age: { $nin: [18, 65] } })
// Mavjudlik tekshirish
db.users.find({ email: { $exists: true } })
db.users.find({ phone: { $exists: false } })
// Null qiymatlar
db.users.find({ bio: { $eq: null } })
db.users.find({ bio: { $ne: null } })
🔤 String Operators
// Matn operatorlari
db.users.find({ username: { $regex: /^j/, $options: 'i' } })
db.users.find({ email: { $regex: /@gmail\.com$/ } })
db.users.find({ firstName: { $regex: /john/i } })
// Matn uzunligi
db.users.find({ bio: { $exists: true, $ne: "" } })
db.users.find({ bio: { $regex: /.{10,}/ } })
🧠 Logical Operators
🔗 AND, OR, NOT
// AND operatori (default)
db.users.find({
age: { $gte: 18 },
isActive: true
})
// OR operatori
db.users.find({
$or: [
{ age: { $gte: 65 } },
{ age: { $lt: 18 } }
]
})
// NOT operatori
db.users.find({
$not: { age: { $gte: 25 } }
})
// Murakkab mantiq
db.users.find({
$and: [
{ isActive: true },
{
$or: [
{ age: { $gte: 18 } },
{ role: "admin" }
]
}
]
})
📊 Array Operators
// Massiv operatorlari
db.users.find({ hobbies: "reading" })
db.users.find({ hobbies: { $all: ["reading", "gaming"] } })
db.users.find({ hobbies: { $size: 3 } })
db.users.find({ hobbies: { $elemMatch: { $regex: /^r/ } } })
// Nested array
db.users.find({
"addresses.city": "New York"
})
db.users.find({
"addresses": {
$elemMatch: {
city: "New York",
isPrimary: true
}
}
})
📈 Aggregation Pipeline
🔧 Pipeline Stages
// Oddiy aggregation
db.users.aggregate([
{ $match: { isActive: true } },
{ $group: {
_id: "$age",
count: { $sum: 1 },
avgScore: { $avg: "$score" }
}},
{ $sort: { count: -1 } },
{ $limit: 10 }
])
// Lookup (JOIN o'rniga)
db.posts.aggregate([
{
$lookup: {
from: "users",
localField: "authorId",
foreignField: "_id",
as: "author"
}
},
{ $unwind: "$author" },
{ $project: {
title: 1,
content: 1,
"author.username": 1,
"author.email": 1
}}
])
📊 Advanced Aggregation
// Murakkab tahlil
db.orders.aggregate([
// Faqat oxirgi 30 kun
{ $match: {
createdAt: { $gte: new Date(Date.now() - 30*24*60*60*1000) }
}},
// Guruhlash
{ $group: {
_id: "$customerId",
totalOrders: { $sum: 1 },
totalAmount: { $sum: "$amount" },
avgAmount: { $avg: "$amount" },
lastOrder: { $max: "$createdAt" }
}},
// Filtrlash
{ $match: { totalOrders: { $gte: 5 } } },
// Tartiblash
{ $sort: { totalAmount: -1 } },
// Cheklash
{ $limit: 10 }
])
📇 Indexing
🔍 Index Turlari
// Oddiy index
db.users.createIndex({ username: 1 })
db.users.createIndex({ email: 1 })
// Compound index
db.users.createIndex({
isActive: 1,
createdAt: -1
})
// Text index
db.posts.createIndex({
title: "text",
content: "text"
})
// Geospatial index
db.locations.createIndex({
coordinates: "2dsphere"
})
// Unique index
db.users.createIndex({
email: 1
}, { unique: true })
// Partial index
db.users.createIndex({
score: 1
}, {
partialFilterExpression: {
isActive: true
}
})
⚡ Performance Tips
- Query patterns - Qanday so'rovlar ko'p ishlatiladi
- Compound indexes - Ko'p ustunli indexlar
- Covered queries - Index orqali to'liq javob
- Index intersection - Bir necha indexni birlashtirish
⚡ Performance Optimization
📊 Query Analysis
// Explain query
db.users.find({
age: { $gte: 25 },
isActive: true
}).explain("executionStats")
// Profiling
db.setProfilingLevel(2, { slowms: 100 })
db.system.profile.find().sort({ ts: -1 }).limit(5)
// Index usage
db.users.aggregate([
{ $indexStats: {} }
])
// Query optimization
db.users.find({
age: { $gte: 25 },
isActive: true
}).hint({ age: 1, isActive: 1 })
✅ Optimization Tips
- Indexes - To'g'ri indexlar
- Projection - Kerakli ustunlar
- Limit - Natijalarni cheklash
- Skip - Skip o'rniga cursor
⚠️ Avoid
- Large documents - Katta hujjatlar
- N+1 queries - Ko'p so'rovlar
- Regex without index - Indexsiz regex
- Large sorts - Katta tartiblash
💼 Real-world Examples
📱 E-commerce Analytics
// Eng ko'p sotilgan mahsulotlar
db.orders.aggregate([
{ $unwind: "$items" },
{ $group: {
_id: "$items.productId",
totalSold: { $sum: "$items.quantity" },
totalRevenue: { $sum: { $multiply: ["$items.quantity", "$items.price"] }}
}},
{ $lookup: {
from: "products",
localField: "_id",
foreignField: "_id",
as: "product"
}},
{ $unwind: "$product" },
{ $project: {
productName: "$product.name",
totalSold: 1,
totalRevenue: 1
}},
{ $sort: { totalSold: -1 } },
{ $limit: 10 }
])
📊 User Behavior Analysis
// Foydalanuvchi faollik tahlili
db.user_activities.aggregate([
{ $match: {
timestamp: { $gte: new Date("2024-01-01") }
}},
{ $group: {
_id: "$userId",
totalActivities: { $sum: 1 },
uniqueDays: { $addToSet: { $dateToString: {
format: "%Y-%m-%d",
date: "$timestamp"
}}},
lastActivity: { $max: "$timestamp" }
}},
{ $addFields: {
activeDays: { $size: "$uniqueDays" }
}},
{ $match: {
totalActivities: { $gte: 10 },
activeDays: { $gte: 5 }
}},
{ $sort: { totalActivities: -1 } }
])
📝 Xulosa
🎯 O'rganilgan Mavzular
- Query operators va mantiqiy operatorlar
- Aggregation pipeline va murakkab tahlil
- Indexing va performance optimization
- Real-world misollar va best practices
- Query analysis va monitoring
✅ Keyingi Qadamlar
- Replica Sets
- Sharding
- Change Streams
- Atlas Cloud
💡 Maslahatlar
- Query patterns'ni tahlil qiling
- Indexlarni optimizatsiya qiling
- Performance monitoring
- Best practices'ga rioya qiling
🏆 Amaliy Mashq
MongoDB bilan to'liq analytics tizimi yarating!