-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path5_indexes_and_aggregation.js
More file actions
166 lines (148 loc) · 4.84 KB
/
Copy path5_indexes_and_aggregation.js
File metadata and controls
166 lines (148 loc) · 4.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
const { connect, closeConnection } = require('./0_connection');
// Index Operations
async function indexExamples() {
const db = await connect();
try {
// Create a single field index
// Docs: https://www.mongodb.com/docs/manual/indexes/
await db.collection('products').createIndex(
{ name: 1 }, // 1 for ascending, -1 for descending
{
name: "idx_product_name",
background: true // Create index in background
}
);
// Create a compound index
await db.collection('products').createIndex(
{
category: 1,
price: -1
},
{
name: "idx_category_price",
background: true
}
);
// Create a unique index
await db.collection('users').createIndex(
{ email: 1 },
{
unique: true,
name: "idx_unique_email"
}
);
// List all indexes on a collection
const productIndexes = await db.collection('products').listIndexes().toArray();
const userIndexes = await db.collection('users').listIndexes().toArray();
console.log('Indexes created:', {
productIndexes,
userIndexes
});
} catch (error) {
console.error('Error in index operations:', error);
}
}
// Aggregation Pipeline Examples
async function aggregationExamples() {
const db = await connect();
try {
// Basic aggregation - Average price by category
// Docs: https://www.mongodb.com/docs/manual/aggregation/
const avgPriceByCategory = await db.collection('products').aggregate([
{
$group: {
_id: "$category",
averagePrice: { $avg: "$price" },
totalProducts: { $sum: 1 }
}
},
{
$sort: { averagePrice: -1 }
}
]).toArray();
// Complex aggregation - Sales analysis
const salesAnalysis = await db.collection('orders').aggregate([
// Unwind the products array
{ $unwind: "$products" },
// Group by product
{
$group: {
_id: "$products.product_id",
totalQuantity: { $sum: "$products.quantity" },
totalRevenue: {
$sum: {
$multiply: ["$products.quantity", "$products.price"]
}
},
averageOrderValue: { $avg: "$products.price" }
}
},
// Lookup product details
{
$lookup: {
from: "products",
localField: "_id",
foreignField: "_id",
as: "product_details"
}
},
// Reshape the output
{
$project: {
productName: { $arrayElemAt: ["$product_details.name", 0] },
category: { $arrayElemAt: ["$product_details.category", 0] },
totalQuantity: 1,
totalRevenue: 1,
averageOrderValue: 1
}
},
// Sort by revenue
{ $sort: { totalRevenue: -1 } }
]).toArray();
// User statistics with multiple stages
const userStats = await db.collection('users').aggregate([
// Match active users
{
$match: {
last_login: {
$gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) // Last 30 days
}
}
},
// Group by age range
{
$bucket: {
groupBy: "$age",
boundaries: [0, 18, 25, 35, 50, 65, 120],
default: "Unknown",
output: {
count: { $sum: 1 },
averageOrderCount: { $avg: "$order_count" },
users: { $push: { username: "$username", age: "$age" } }
}
}
}
]).toArray();
console.log('Aggregation results:', {
avgPriceByCategory,
salesAnalysis,
userStats
});
} catch (error) {
console.error('Error in aggregation operations:', error);
} finally {
await closeConnection();
}
}
// Run all examples if this file is run directly
if (require.main === module) {
async function runAll() {
await indexExamples();
await aggregationExamples();
}
runAll();
}
module.exports = {
indexExamples,
aggregationExamples
};