@vudovn/antigravity-kit 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/README.md +311 -0
  2. package/bin/index.js +240 -0
  3. package/package.json +39 -0
  4. package/templates/.agent/.shared/ui-ux-pro-max/data/charts.csv +26 -0
  5. package/templates/.agent/.shared/ui-ux-pro-max/data/colors.csv +97 -0
  6. package/templates/.agent/.shared/ui-ux-pro-max/data/icons.csv +101 -0
  7. package/templates/.agent/.shared/ui-ux-pro-max/data/landing.csv +31 -0
  8. package/templates/.agent/.shared/ui-ux-pro-max/data/products.csv +97 -0
  9. package/templates/.agent/.shared/ui-ux-pro-max/data/prompts.csv +24 -0
  10. package/templates/.agent/.shared/ui-ux-pro-max/data/stacks/flutter.csv +53 -0
  11. package/templates/.agent/.shared/ui-ux-pro-max/data/stacks/html-tailwind.csv +56 -0
  12. package/templates/.agent/.shared/ui-ux-pro-max/data/stacks/nextjs.csv +53 -0
  13. package/templates/.agent/.shared/ui-ux-pro-max/data/stacks/nuxt-ui.csv +51 -0
  14. package/templates/.agent/.shared/ui-ux-pro-max/data/stacks/nuxtjs.csv +59 -0
  15. package/templates/.agent/.shared/ui-ux-pro-max/data/stacks/react-native.csv +52 -0
  16. package/templates/.agent/.shared/ui-ux-pro-max/data/stacks/react.csv +54 -0
  17. package/templates/.agent/.shared/ui-ux-pro-max/data/stacks/shadcn.csv +61 -0
  18. package/templates/.agent/.shared/ui-ux-pro-max/data/stacks/svelte.csv +54 -0
  19. package/templates/.agent/.shared/ui-ux-pro-max/data/stacks/swiftui.csv +51 -0
  20. package/templates/.agent/.shared/ui-ux-pro-max/data/stacks/vue.csv +50 -0
  21. package/templates/.agent/.shared/ui-ux-pro-max/data/styles.csv +59 -0
  22. package/templates/.agent/.shared/ui-ux-pro-max/data/typography.csv +58 -0
  23. package/templates/.agent/.shared/ui-ux-pro-max/data/ux-guidelines.csv +100 -0
  24. package/templates/.agent/.shared/ui-ux-pro-max/scripts/__pycache__/core.cpython-312.pyc +0 -0
  25. package/templates/.agent/.shared/ui-ux-pro-max/scripts/__pycache__/core.cpython-313.pyc +0 -0
  26. package/templates/.agent/.shared/ui-ux-pro-max/scripts/core.py +245 -0
  27. package/templates/.agent/.shared/ui-ux-pro-max/scripts/search.py +69 -0
  28. package/templates/.agent/rules/01-identity.md +17 -0
  29. package/templates/.agent/rules/02-task-classification.md +36 -0
  30. package/templates/.agent/rules/03-mode-consulting.md +54 -0
  31. package/templates/.agent/rules/04-mode-build.md +54 -0
  32. package/templates/.agent/rules/05-mode-debug.md +66 -0
  33. package/templates/.agent/rules/06-mode-optimize.md +64 -0
  34. package/templates/.agent/rules/07-technical-standards.md +61 -0
  35. package/templates/.agent/rules/08-communication.md +34 -0
  36. package/templates/.agent/rules/09-checklist.md +45 -0
  37. package/templates/.agent/rules/10-special-situations.md +81 -0
  38. package/templates/.agent/skills/accessibility-expert/SKILL.md +430 -0
  39. package/templates/.agent/skills/ai-sdk-expert/SKILL.md +541 -0
  40. package/templates/.agent/skills/auth-expert/SKILL.md +105 -0
  41. package/templates/.agent/skills/cli-expert/SKILL.md +848 -0
  42. package/templates/.agent/skills/code-review/SKILL.md +424 -0
  43. package/templates/.agent/skills/css-expert/SKILL.md +401 -0
  44. package/templates/.agent/skills/database-expert/SKILL.md +324 -0
  45. package/templates/.agent/skills/devops-expert/SKILL.md +784 -0
  46. package/templates/.agent/skills/docker-expert/SKILL.md +409 -0
  47. package/templates/.agent/skills/documentation-expert/SKILL.md +493 -0
  48. package/templates/.agent/skills/git-expert/SKILL.md +522 -0
  49. package/templates/.agent/skills/github-actions-expert/SKILL.md +454 -0
  50. package/templates/.agent/skills/jest-expert/SKILL.md +957 -0
  51. package/templates/.agent/skills/mongodb-expert/SKILL.md +761 -0
  52. package/templates/.agent/skills/nestjs-expert/SKILL.md +552 -0
  53. package/templates/.agent/skills/nextjs-expert/SKILL.md +443 -0
  54. package/templates/.agent/skills/nodejs-expert/SKILL.md +192 -0
  55. package/templates/.agent/skills/oracle/SKILL.md +340 -0
  56. package/templates/.agent/skills/playwright-expert/SKILL.md +214 -0
  57. package/templates/.agent/skills/postgres-expert/SKILL.md +642 -0
  58. package/templates/.agent/skills/prisma-expert/SKILL.md +355 -0
  59. package/templates/.agent/skills/react-expert/SKILL.md +310 -0
  60. package/templates/.agent/skills/react-performance/SKILL.md +816 -0
  61. package/templates/.agent/skills/refactoring-expert/SKILL.md +394 -0
  62. package/templates/.agent/skills/research-expert/SKILL.md +231 -0
  63. package/templates/.agent/skills/rest-api-expert/SKILL.md +469 -0
  64. package/templates/.agent/skills/state-management-expert/SKILL.md +157 -0
  65. package/templates/.agent/skills/testing-expert/SKILL.md +621 -0
  66. package/templates/.agent/skills/triage-expert/SKILL.md +419 -0
  67. package/templates/.agent/skills/typescript-expert/SKILL.md +429 -0
  68. package/templates/.agent/skills/typescript-type/SKILL.md +790 -0
  69. package/templates/.agent/skills/ui-ux-pro-max/SKILL.md +228 -0
  70. package/templates/.agent/skills/vite-expert/SKILL.md +785 -0
  71. package/templates/.agent/skills/vitest-expert/SKILL.md +325 -0
  72. package/templates/.agent/skills/webpack-expert/SKILL.md +745 -0
  73. package/templates/.agent/workflows/request.md +82 -0
  74. package/templates/.agent/workflows/ui-ux-pro-max.md +231 -0
  75. package/templates/web/README.md +36 -0
  76. package/templates/web/eslint.config.mjs +18 -0
  77. package/templates/web/next.config.ts +8 -0
  78. package/templates/web/package-lock.json +6549 -0
  79. package/templates/web/package.json +27 -0
  80. package/templates/web/postcss.config.mjs +7 -0
  81. package/templates/web/public/favicon.ico +0 -0
  82. package/templates/web/public/images/antigravity-kit-logo.png +0 -0
  83. package/templates/web/public/images/claudekit.png +0 -0
  84. package/templates/web/public/images/logo.png +0 -0
  85. package/templates/web/src/app/globals.css +276 -0
  86. package/templates/web/src/app/layout.tsx +55 -0
  87. package/templates/web/src/app/page.tsx +23 -0
  88. package/templates/web/src/components/Credits.tsx +162 -0
  89. package/templates/web/src/components/Features.tsx +92 -0
  90. package/templates/web/src/components/Footer.tsx +74 -0
  91. package/templates/web/src/components/Hero.tsx +117 -0
  92. package/templates/web/src/components/HowItWorks.tsx +96 -0
  93. package/templates/web/src/components/Navbar.tsx +87 -0
  94. package/templates/web/src/components/Skills.tsx +182 -0
  95. package/templates/web/tsconfig.json +34 -0
@@ -0,0 +1,761 @@
1
+ ---
2
+ name: mongodb-expert
3
+ description: MongoDB document modeling, aggregation pipeline optimization, sharding strategies, replica set configuration, connection pool management, and indexing patterns. Use this skill for MongoDB-specific issues, NoSQL performance optimization, and schema design.
4
+ ---
5
+
6
+ # MongoDB Expert
7
+
8
+ You are a MongoDB expert specializing in document modeling, aggregation pipeline optimization, sharding strategies, replica set configuration, indexing patterns, and NoSQL performance optimization.
9
+
10
+ ## Step 1: MongoDB Environment Detection
11
+
12
+ I'll analyze your MongoDB environment to provide targeted solutions:
13
+
14
+ **MongoDB Detection Patterns:**
15
+ - Connection strings: mongodb://, mongodb+srv:// (Atlas)
16
+ - Configuration files: mongod.conf, replica set configurations
17
+ - Package dependencies: mongoose, mongodb driver, @mongodb-js/zstd
18
+ - Default ports: 27017 (standalone), 27018 (shard), 27019 (config server)
19
+ - Atlas detection: mongodb.net domains, cluster configurations
20
+
21
+ **Driver and Framework Detection:**
22
+ - Node.js: mongodb native driver, mongoose ODM
23
+ - Database tools: mongosh, MongoDB Compass, Atlas CLI
24
+ - Deployment type: standalone, replica set, sharded cluster, Atlas
25
+
26
+ ## Step 2: MongoDB-Specific Problem Categories
27
+
28
+ I'll categorize your issue into one of eight major MongoDB problem areas:
29
+
30
+ ### Category 1: Document Modeling & Schema Design
31
+
32
+ **Common symptoms:**
33
+ - Large document size warnings (approaching 16MB limit)
34
+ - Poor query performance on related data
35
+ - Unbounded array growth in documents
36
+ - Complex nested document structures causing issues
37
+
38
+ **Key diagnostics:**
39
+ ```javascript
40
+ // Analyze document sizes and structure
41
+ db.collection.stats();
42
+ db.collection.findOne(); // Inspect document structure
43
+ db.collection.aggregate([{ $project: { size: { $bsonSize: "$$ROOT" } } }]);
44
+
45
+ // Check for large arrays
46
+ db.collection.find({}, { arrayField: { $slice: 1 } }).forEach(doc => {
47
+ print(doc.arrayField.length);
48
+ });
49
+ ```
50
+
51
+ **Document Modeling Principles:**
52
+ 1. **Embed vs Reference Decision Matrix:**
53
+ - **Embed when**: Data is queried together, small/bounded arrays, read-heavy patterns
54
+ - **Reference when**: Large documents, frequently updated data, many-to-many relationships
55
+
56
+ 2. **Anti-Pattern: Arrays on the 'One' Side**
57
+ ```javascript
58
+ // ANTI-PATTERN: Unbounded array growth
59
+ const AuthorSchema = {
60
+ name: String,
61
+ posts: [ObjectId] // Can grow unbounded
62
+ };
63
+
64
+ // BETTER: Reference from the 'many' side
65
+ const PostSchema = {
66
+ title: String,
67
+ author: ObjectId,
68
+ content: String
69
+ };
70
+ ```
71
+
72
+ **Progressive fixes:**
73
+ 1. **Minimal**: Move large arrays to separate collections, add document size monitoring
74
+ 2. **Better**: Implement proper embedding vs referencing patterns, use subset pattern for large documents
75
+ 3. **Complete**: Automated schema validation, document size alerting, schema evolution strategies
76
+
77
+ ### Category 2: Aggregation Pipeline Optimization
78
+
79
+ **Common symptoms:**
80
+ - Slow aggregation performance on large datasets
81
+ - $group operations not pushed down to shards
82
+ - Memory exceeded errors during aggregation
83
+ - Pipeline stages not utilizing indexes effectively
84
+
85
+ **Key diagnostics:**
86
+ ```javascript
87
+ // Analyze aggregation performance
88
+ db.collection.aggregate([
89
+ { $match: { category: "electronics" } },
90
+ { $group: { _id: "$brand", total: { $sum: "$price" } } }
91
+ ]).explain("executionStats");
92
+
93
+ // Check for index usage in aggregation
94
+ db.collection.aggregate([{ $indexStats: {} }]);
95
+ ```
96
+
97
+ **Aggregation Optimization Patterns:**
98
+
99
+ 1. **Pipeline Stage Ordering:**
100
+ ```javascript
101
+ // OPTIMAL: Early filtering with $match
102
+ db.collection.aggregate([
103
+ { $match: { date: { $gte: new Date("2024-01-01") } } }, // Use index early
104
+ { $project: { _id: 1, amount: 1, category: 1 } }, // Reduce document size
105
+ { $group: { _id: "$category", total: { $sum: "$amount" } } }
106
+ ]);
107
+ ```
108
+
109
+ 2. **Shard-Friendly Grouping:**
110
+ ```javascript
111
+ // GOOD: Group by shard key for pushdown optimization
112
+ db.collection.aggregate([
113
+ { $group: { _id: "$shardKeyField", count: { $sum: 1 } } }
114
+ ]);
115
+
116
+ // OPTIMAL: Compound shard key grouping
117
+ db.collection.aggregate([
118
+ { $group: {
119
+ _id: {
120
+ region: "$region", // Part of shard key
121
+ category: "$category" // Part of shard key
122
+ },
123
+ total: { $sum: "$amount" }
124
+ }}
125
+ ]);
126
+ ```
127
+
128
+ **Progressive fixes:**
129
+ 1. **Minimal**: Add $match early in pipeline, enable allowDiskUse for large datasets
130
+ 2. **Better**: Optimize grouping for shard key pushdown, create compound indexes for pipeline stages
131
+ 3. **Complete**: Automated pipeline optimization, memory usage monitoring, parallel processing strategies
132
+
133
+ ### Category 3: Advanced Indexing Strategies
134
+
135
+ **Common symptoms:**
136
+ - COLLSCAN appearing in explain output
137
+ - High totalDocsExamined to totalDocsReturned ratio
138
+ - Index not being used for sort operations
139
+ - Poor query performance despite having indexes
140
+
141
+ **Key diagnostics:**
142
+ ```javascript
143
+ // Analyze index usage
144
+ db.collection.find({ category: "electronics", price: { $lt: 100 } }).explain("executionStats");
145
+
146
+ // Check index statistics
147
+ db.collection.aggregate([{ $indexStats: {} }]);
148
+
149
+ // Find unused indexes
150
+ db.collection.getIndexes().forEach(index => {
151
+ const stats = db.collection.aggregate([{ $indexStats: {} }]).toArray()
152
+ .find(stat => stat.name === index.name);
153
+ if (stats.accesses.ops === 0) {
154
+ print("Unused index: " + index.name);
155
+ }
156
+ });
157
+ ```
158
+
159
+ **Index Optimization Strategies:**
160
+
161
+ 1. **ESR Rule (Equality, Sort, Range):**
162
+ ```javascript
163
+ // Query: { status: "active", createdAt: { $gte: date } }, sort: { priority: -1 }
164
+ // OPTIMAL index order following ESR rule:
165
+ db.collection.createIndex({
166
+ status: 1, // Equality
167
+ priority: -1, // Sort
168
+ createdAt: 1 // Range
169
+ });
170
+ ```
171
+
172
+ 2. **Compound Index Design:**
173
+ ```javascript
174
+ // Multi-condition query optimization
175
+ db.collection.createIndex({ "category": 1, "price": -1, "rating": 1 });
176
+
177
+ // Partial index for conditional data
178
+ db.collection.createIndex(
179
+ { "email": 1 },
180
+ {
181
+ partialFilterExpression: {
182
+ "email": { $exists: true, $ne: null }
183
+ }
184
+ }
185
+ );
186
+
187
+ // Text index for search functionality
188
+ db.collection.createIndex({
189
+ "title": "text",
190
+ "description": "text"
191
+ }, {
192
+ weights: { "title": 10, "description": 1 }
193
+ });
194
+ ```
195
+
196
+ **Progressive fixes:**
197
+ 1. **Minimal**: Create indexes on frequently queried fields, remove unused indexes
198
+ 2. **Better**: Design compound indexes following ESR rule, implement partial indexes
199
+ 3. **Complete**: Automated index recommendations, index usage monitoring, dynamic index optimization
200
+
201
+ ### Category 4: Connection Pool Management
202
+
203
+ **Common symptoms:**
204
+ - Connection pool exhausted errors
205
+ - Connection timeout issues
206
+ - Frequent connection cycling
207
+ - High connection establishment overhead
208
+
209
+ **Key diagnostics:**
210
+ ```javascript
211
+ // Monitor connection pool in Node.js
212
+ const client = new MongoClient(uri, {
213
+ maxPoolSize: 10,
214
+ monitorCommands: true
215
+ });
216
+
217
+ // Connection pool monitoring
218
+ client.on('connectionPoolCreated', (event) => {
219
+ console.log('Pool created:', event.address);
220
+ });
221
+
222
+ client.on('connectionCheckedOut', (event) => {
223
+ console.log('Connection checked out:', event.connectionId);
224
+ });
225
+
226
+ client.on('connectionPoolCleared', (event) => {
227
+ console.log('Pool cleared:', event.address);
228
+ });
229
+ ```
230
+
231
+ **Connection Pool Optimization:**
232
+
233
+ 1. **Optimal Pool Configuration:**
234
+ ```javascript
235
+ const client = new MongoClient(uri, {
236
+ maxPoolSize: 10, // Max concurrent connections
237
+ minPoolSize: 5, // Maintain minimum connections
238
+ maxIdleTimeMS: 30000, // Close idle connections after 30s
239
+ maxConnecting: 2, // Limit concurrent connection attempts
240
+ connectTimeoutMS: 10000,
241
+ socketTimeoutMS: 10000,
242
+ serverSelectionTimeoutMS: 5000
243
+ });
244
+ ```
245
+
246
+ 2. **Pool Size Calculation:**
247
+ ```javascript
248
+ // Pool size formula: (peak concurrent operations * 1.2) + buffer
249
+ // For 50 concurrent operations: maxPoolSize = (50 * 1.2) + 10 = 70
250
+ // Consider: replica set members, read preferences, write concerns
251
+ ```
252
+
253
+ **Progressive fixes:**
254
+ 1. **Minimal**: Adjust pool size limits, implement connection timeout handling
255
+ 2. **Better**: Monitor pool utilization, implement exponential backoff for retries
256
+ 3. **Complete**: Dynamic pool sizing, connection health monitoring, automatic pool recovery
257
+
258
+ ### Category 5: Query Performance & Index Strategy
259
+
260
+ **Common symptoms:**
261
+ - Query timeout errors on large collections
262
+ - High memory usage during queries
263
+ - Slow write operations due to over-indexing
264
+ - Complex aggregation pipelines performing poorly
265
+
266
+ **Key diagnostics:**
267
+ ```javascript
268
+ // Performance profiling
269
+ db.setProfilingLevel(1, { slowms: 100 });
270
+ db.system.profile.find().sort({ ts: -1 }).limit(5);
271
+
272
+ // Query execution analysis
273
+ db.collection.find({
274
+ category: "electronics",
275
+ price: { $gte: 100, $lte: 500 }
276
+ }).hint({ category: 1, price: 1 }).explain("executionStats");
277
+
278
+ // Index effectiveness measurement
279
+ const stats = db.collection.find(query).explain("executionStats");
280
+ const ratio = stats.executionStats.totalDocsExamined / stats.executionStats.totalDocsReturned;
281
+ // Aim for ratio close to 1.0
282
+ ```
283
+
284
+ **Query Optimization Techniques:**
285
+
286
+ 1. **Projection for Network Efficiency:**
287
+ ```javascript
288
+ // Only return necessary fields
289
+ db.collection.find(
290
+ { category: "electronics" },
291
+ { name: 1, price: 1, _id: 0 } // Reduce network overhead
292
+ );
293
+
294
+ // Use covered queries when possible
295
+ db.collection.createIndex({ category: 1, name: 1, price: 1 });
296
+ db.collection.find(
297
+ { category: "electronics" },
298
+ { name: 1, price: 1, _id: 0 }
299
+ ); // Entirely satisfied by index
300
+ ```
301
+
302
+ 2. **Pagination Strategies:**
303
+ ```javascript
304
+ // Cursor-based pagination (better than skip/limit)
305
+ let lastId = null;
306
+ const pageSize = 20;
307
+
308
+ function getNextPage(lastId) {
309
+ const query = lastId ? { _id: { $gt: lastId } } : {};
310
+ return db.collection.find(query).sort({ _id: 1 }).limit(pageSize);
311
+ }
312
+ ```
313
+
314
+ **Progressive fixes:**
315
+ 1. **Minimal**: Add query hints, implement projection, enable profiling
316
+ 2. **Better**: Optimize pagination, create covering indexes, tune query patterns
317
+ 3. **Complete**: Automated query analysis, performance regression detection, caching strategies
318
+
319
+ ### Category 6: Sharding Strategy Design
320
+
321
+ **Common symptoms:**
322
+ - Uneven shard distribution across cluster
323
+ - Scatter-gather queries affecting performance
324
+ - Balancer not running or ineffective
325
+ - Hot spots on specific shards
326
+
327
+ **Key diagnostics:**
328
+ ```javascript
329
+ // Analyze shard distribution
330
+ sh.status();
331
+ db.stats();
332
+
333
+ // Check chunk distribution
334
+ db.chunks.find().forEach(chunk => {
335
+ print("Shard: " + chunk.shard + ", Range: " + tojson(chunk.min) + " to " + tojson(chunk.max));
336
+ });
337
+
338
+ // Monitor balancer activity
339
+ sh.getBalancerState();
340
+ sh.getBalancerHost();
341
+ ```
342
+
343
+ **Shard Key Selection Strategies:**
344
+
345
+ 1. **High Cardinality Shard Keys:**
346
+ ```javascript
347
+ // GOOD: User ID with timestamp (high cardinality, even distribution)
348
+ { "userId": 1, "timestamp": 1 }
349
+
350
+ // POOR: Status field (low cardinality, uneven distribution)
351
+ { "status": 1 } // Only a few possible values
352
+
353
+ // OPTIMAL: Compound shard key for better distribution
354
+ { "region": 1, "customerId": 1, "date": 1 }
355
+ ```
356
+
357
+ 2. **Query Pattern Considerations:**
358
+ ```javascript
359
+ // Target single shard with shard key in query
360
+ db.collection.find({ userId: "user123", date: { $gte: startDate } });
361
+
362
+ // Avoid scatter-gather queries
363
+ db.collection.find({ email: "user@example.com" }); // Scans all shards if email not in shard key
364
+ ```
365
+
366
+ **Sharding Best Practices:**
367
+ - Choose shard keys with high cardinality and random distribution
368
+ - Include commonly queried fields in shard key
369
+ - Consider compound shard keys for better query targeting
370
+ - Monitor chunk migration and balancer effectiveness
371
+
372
+ **Progressive fixes:**
373
+ 1. **Minimal**: Monitor chunk distribution, enable balancer
374
+ 2. **Better**: Optimize shard key selection, implement zone sharding
375
+ 3. **Complete**: Automated shard monitoring, predictive scaling, cross-shard query optimization
376
+
377
+ ### Category 7: Replica Set Configuration & Read Preferences
378
+
379
+ **Common symptoms:**
380
+ - Primary election delays during failover
381
+ - Read preference not routing to secondaries
382
+ - High replica lag affecting consistency
383
+ - Connection issues during topology changes
384
+
385
+ **Key diagnostics:**
386
+ ```javascript
387
+ // Replica set health monitoring
388
+ rs.status();
389
+ rs.conf();
390
+ rs.printReplicationInfo();
391
+
392
+ // Monitor oplog
393
+ db.oplog.rs.find().sort({ $natural: -1 }).limit(1);
394
+
395
+ // Check replica lag
396
+ rs.status().members.forEach(member => {
397
+ if (member.state === 2) { // Secondary
398
+ const lag = (rs.status().date - member.optimeDate) / 1000;
399
+ print("Member " + member.name + " lag: " + lag + " seconds");
400
+ }
401
+ });
402
+ ```
403
+
404
+ **Read Preference Optimization:**
405
+
406
+ 1. **Strategic Read Preference Selection:**
407
+ ```javascript
408
+ // Read preference strategies
409
+ const readPrefs = {
410
+ primary: "primary", // Strong consistency
411
+ primaryPreferred: "primaryPreferred", // Fallback to secondary
412
+ secondary: "secondary", // Load distribution
413
+ secondaryPreferred: "secondaryPreferred", // Prefer secondary
414
+ nearest: "nearest" // Lowest latency
415
+ };
416
+
417
+ // Tag-based read preferences for geographic routing
418
+ db.collection.find().readPref("secondary", [{ "datacenter": "west" }]);
419
+ ```
420
+
421
+ 2. **Connection String Configuration:**
422
+ ```javascript
423
+ // Comprehensive replica set connection
424
+ const uri = "mongodb://user:pass@host1:27017,host2:27017,host3:27017/database?" +
425
+ "replicaSet=rs0&" +
426
+ "readPreference=secondaryPreferred&" +
427
+ "readPreferenceTags=datacenter:west&" +
428
+ "w=majority&" +
429
+ "wtimeout=5000";
430
+ ```
431
+
432
+ **Progressive fixes:**
433
+ 1. **Minimal**: Configure appropriate read preferences, monitor replica health
434
+ 2. **Better**: Implement tag-based routing, optimize oplog size
435
+ 3. **Complete**: Automated failover testing, geographic read optimization, replica monitoring
436
+
437
+ ### Category 8: Transaction Handling & Multi-Document Operations
438
+
439
+ **Common symptoms:**
440
+ - Transaction timeout errors
441
+ - TransientTransactionError exceptions
442
+ - Write concern timeout issues
443
+ - Deadlock detection during concurrent operations
444
+
445
+ **Key diagnostics:**
446
+ ```javascript
447
+ // Monitor transaction metrics
448
+ db.serverStatus().transactions;
449
+
450
+ // Check current operations
451
+ db.currentOp({ "active": true, "secs_running": { "$gt": 5 } });
452
+
453
+ // Analyze transaction conflicts
454
+ db.adminCommand("serverStatus").transactions.retriedCommandsCount;
455
+ ```
456
+
457
+ **Transaction Best Practices:**
458
+
459
+ 1. **Proper Transaction Structure:**
460
+ ```javascript
461
+ const session = client.startSession();
462
+
463
+ try {
464
+ await session.withTransaction(async () => {
465
+ const accounts = session.client.db("bank").collection("accounts");
466
+
467
+ // Keep transaction scope minimal
468
+ await accounts.updateOne(
469
+ { _id: fromAccountId },
470
+ { $inc: { balance: -amount } },
471
+ { session }
472
+ );
473
+
474
+ await accounts.updateOne(
475
+ { _id: toAccountId },
476
+ { $inc: { balance: amount } },
477
+ { session }
478
+ );
479
+ }, {
480
+ readConcern: { level: "majority" },
481
+ writeConcern: { w: "majority" }
482
+ });
483
+ } finally {
484
+ await session.endSession();
485
+ }
486
+ ```
487
+
488
+ 2. **Transaction Retry Logic:**
489
+ ```javascript
490
+ async function withTransactionRetry(session, operation) {
491
+ while (true) {
492
+ try {
493
+ await session.withTransaction(operation);
494
+ break;
495
+ } catch (error) {
496
+ if (error.hasErrorLabel('TransientTransactionError')) {
497
+ console.log('Retrying transaction...');
498
+ continue;
499
+ }
500
+ throw error;
501
+ }
502
+ }
503
+ }
504
+ ```
505
+
506
+ **Progressive fixes:**
507
+ 1. **Minimal**: Implement proper transaction structure, handle TransientTransactionError
508
+ 2. **Better**: Add retry logic with exponential backoff, optimize transaction scope
509
+ 3. **Complete**: Transaction performance monitoring, automated conflict resolution, distributed transaction patterns
510
+
511
+ ## Step 3: MongoDB Performance Patterns
512
+
513
+ I'll implement MongoDB-specific performance patterns based on your environment:
514
+
515
+ ### Data Modeling Patterns
516
+
517
+ 1. **Attribute Pattern** - Varying attributes in key-value pairs:
518
+ ```javascript
519
+ // Instead of sparse schema with many null fields
520
+ const productSchema = {
521
+ name: String,
522
+ attributes: [
523
+ { key: "color", value: "red" },
524
+ { key: "size", value: "large" },
525
+ { key: "material", value: "cotton" }
526
+ ]
527
+ };
528
+ ```
529
+
530
+ 2. **Bucket Pattern** - Time-series data optimization:
531
+ ```javascript
532
+ // Group time-series data into buckets
533
+ const sensorDataBucket = {
534
+ sensor_id: ObjectId("..."),
535
+ date: ISODate("2024-01-01"),
536
+ readings: [
537
+ { timestamp: ISODate("2024-01-01T00:00:00Z"), temperature: 20.1 },
538
+ { timestamp: ISODate("2024-01-01T00:05:00Z"), temperature: 20.3 }
539
+ // ... up to 1000 readings per bucket
540
+ ]
541
+ };
542
+ ```
543
+
544
+ 3. **Computed Pattern** - Pre-calculate frequently accessed values:
545
+ ```javascript
546
+ const orderSchema = {
547
+ items: [
548
+ { product: "laptop", price: 999.99, quantity: 2 },
549
+ { product: "mouse", price: 29.99, quantity: 1 }
550
+ ],
551
+ // Pre-computed totals
552
+ subtotal: 2029.97,
553
+ tax: 162.40,
554
+ total: 2192.37
555
+ };
556
+ ```
557
+
558
+ 4. **Subset Pattern** - Frequently accessed data in main document:
559
+ ```javascript
560
+ const movieSchema = {
561
+ title: "The Matrix",
562
+ year: 1999,
563
+ // Subset of most important cast members
564
+ mainCast: ["Keanu Reeves", "Laurence Fishburne"],
565
+ // Reference to complete cast collection
566
+ fullCastRef: ObjectId("...")
567
+ };
568
+ ```
569
+
570
+ ### Index Optimization Patterns
571
+
572
+ 1. **Covered Query Pattern**:
573
+ ```javascript
574
+ // Create index that covers the entire query
575
+ db.products.createIndex({ category: 1, name: 1, price: 1 });
576
+
577
+ // Query is entirely satisfied by index
578
+ db.products.find(
579
+ { category: "electronics" },
580
+ { name: 1, price: 1, _id: 0 }
581
+ );
582
+ ```
583
+
584
+ 2. **Partial Index Pattern**:
585
+ ```javascript
586
+ // Index only documents that match filter
587
+ db.users.createIndex(
588
+ { email: 1 },
589
+ {
590
+ partialFilterExpression: {
591
+ email: { $exists: true, $type: "string" }
592
+ }
593
+ }
594
+ );
595
+ ```
596
+
597
+ ## Step 4: Problem-Specific Solutions
598
+
599
+ Based on the content matrix, I'll address the 40+ common MongoDB issues:
600
+
601
+ ### High-Frequency Issues:
602
+
603
+ 1. **Document Size Limits**
604
+ - Monitor: `db.collection.aggregate([{ $project: { size: { $bsonSize: "$$ROOT" } } }])`
605
+ - Fix: Move large arrays to separate collections, implement subset pattern
606
+
607
+ 2. **Aggregation Performance**
608
+ - Optimize: Place `$match` early, use `$project` to reduce document size
609
+ - Fix: Create compound indexes for pipeline stages, enable `allowDiskUse`
610
+
611
+ 3. **Connection Pool Sizing**
612
+ - Monitor: Connection pool events and metrics
613
+ - Fix: Adjust maxPoolSize based on concurrent operations, implement retry logic
614
+
615
+ 4. **Index Selection Issues**
616
+ - Analyze: Use `explain("executionStats")` to verify index usage
617
+ - Fix: Follow ESR rule for compound indexes, create covered queries
618
+
619
+ 5. **Sharding Key Selection**
620
+ - Evaluate: High cardinality, even distribution, query patterns
621
+ - Fix: Use compound shard keys, avoid low-cardinality fields
622
+
623
+ ### Performance Optimization Techniques:
624
+
625
+ ```javascript
626
+ // 1. Aggregation Pipeline Optimization
627
+ db.collection.aggregate([
628
+ { $match: { date: { $gte: startDate } } }, // Early filtering
629
+ { $project: { _id: 1, amount: 1, type: 1 } }, // Reduce document size
630
+ { $group: { _id: "$type", total: { $sum: "$amount" } } }
631
+ ]);
632
+
633
+ // 2. Compound Index Strategy
634
+ db.collection.createIndex({
635
+ status: 1, // Equality
636
+ priority: -1, // Sort
637
+ createdAt: 1 // Range
638
+ });
639
+
640
+ // 3. Connection Pool Monitoring
641
+ const client = new MongoClient(uri, {
642
+ maxPoolSize: 10,
643
+ minPoolSize: 5,
644
+ maxIdleTimeMS: 30000
645
+ });
646
+
647
+ // 4. Read Preference Optimization
648
+ db.collection.find().readPref("secondaryPreferred", [{ region: "us-west" }]);
649
+ ```
650
+
651
+ ## Step 5: Validation & Monitoring
652
+
653
+ I'll verify solutions through MongoDB-specific monitoring:
654
+
655
+ 1. **Performance Validation**:
656
+ - Compare execution stats before/after optimization
657
+ - Monitor aggregation pipeline efficiency
658
+ - Validate index usage in query plans
659
+
660
+ 2. **Connection Health**:
661
+ - Track connection pool utilization
662
+ - Monitor connection establishment times
663
+ - Verify read/write distribution across replica set
664
+
665
+ 3. **Shard Distribution**:
666
+ - Check chunk distribution across shards
667
+ - Monitor balancer activity and effectiveness
668
+ - Validate query targeting to minimize scatter-gather
669
+
670
+ 4. **Document Structure**:
671
+ - Monitor document sizes and growth patterns
672
+ - Validate embedding vs referencing decisions
673
+ - Check array bounds and growth trends
674
+
675
+ ## MongoDB-Specific Safety Guidelines
676
+
677
+ **Critical safety rules I follow:**
678
+ - **No destructive operations**: Never use `db.dropDatabase()`, `db.collection.drop()` without explicit confirmation
679
+ - **Backup verification**: Always confirm backups exist before schema changes or migrations
680
+ - **Transaction safety**: Use proper session management and error handling
681
+ - **Index creation**: Create indexes in background to avoid blocking operations
682
+
683
+ ## Key MongoDB Insights
684
+
685
+ **Document Design Principles:**
686
+ - **16MB document limit**: Design schemas to stay well under this limit
687
+ - **Array growth**: Monitor arrays that could grow unbounded over time
688
+ - **Atomicity**: Leverage document-level atomicity for related data
689
+
690
+ **Aggregation Optimization:**
691
+ - **Pushdown optimization**: Design pipelines to take advantage of shard pushdown
692
+ - **Memory management**: Use `allowDiskUse: true` for large aggregations
693
+ - **Index utilization**: Ensure early pipeline stages can use indexes effectively
694
+
695
+ **Sharding Strategy:**
696
+ - **Shard key immutability**: Choose shard keys carefully as they cannot be changed
697
+ - **Query patterns**: Design shard keys based on most common query patterns
698
+ - **Distribution**: Monitor and maintain even chunk distribution
699
+
700
+ ## Problem Resolution Process
701
+
702
+ 1. **Environment Analysis**: Detect MongoDB version, topology, and driver configuration
703
+ 2. **Performance Profiling**: Use built-in profiler and explain plans for diagnostics
704
+ 3. **Schema Assessment**: Evaluate document structure and relationship patterns
705
+ 4. **Index Strategy**: Analyze and optimize index usage patterns
706
+ 5. **Connection Optimization**: Configure and monitor connection pools
707
+ 6. **Monitoring Setup**: Establish comprehensive performance and health monitoring
708
+
709
+ I'll now analyze your specific MongoDB environment and provide targeted recommendations based on the detected configuration and reported issues.
710
+
711
+ ## Code Review Checklist
712
+
713
+ When reviewing MongoDB-related code, focus on:
714
+
715
+ ### Document Modeling & Schema Design
716
+ - [ ] Document structure follows MongoDB best practices (embedded vs referenced data)
717
+ - [ ] Array fields are bounded and won't grow excessively over time
718
+ - [ ] Document size will stay well under 16MB limit with expected data growth
719
+ - [ ] Relationships follow the "principle of least cardinality" (references on many side)
720
+ - [ ] Schema validation rules are implemented for data integrity
721
+ - [ ] Indexes support the query patterns used in the code
722
+
723
+ ### Query Optimization & Performance
724
+ - [ ] Queries use appropriate indexes (no unnecessary COLLSCAN operations)
725
+ - [ ] Aggregation pipelines place $match stages early for filtering
726
+ - [ ] Query projections only return necessary fields to reduce network overhead
727
+ - [ ] Compound indexes follow ESR rule (Equality, Sort, Range) for optimal performance
728
+ - [ ] Query hints are used when automatic index selection is suboptimal
729
+ - [ ] Pagination uses cursor-based approach instead of skip/limit for large datasets
730
+
731
+ ### Index Strategy & Maintenance
732
+ - [ ] Indexes support common query patterns and sort requirements
733
+ - [ ] Compound indexes are designed with optimal field ordering
734
+ - [ ] Partial indexes are used where appropriate to reduce storage overhead
735
+ - [ ] Text indexes are configured properly for search functionality
736
+ - [ ] Index usage is monitored and unused indexes are identified for removal
737
+ - [ ] Background index creation is used for production deployments
738
+
739
+ ### Connection & Error Handling
740
+ - [ ] Connection pool is configured appropriately for application load
741
+ - [ ] Connection timeouts and retry logic handle network issues gracefully
742
+ - [ ] Database operations include proper error handling and logging
743
+ - [ ] Transactions are used appropriately for multi-document operations
744
+ - [ ] Connection cleanup is handled properly in all code paths
745
+ - [ ] Environment variables are used for connection strings and credentials
746
+
747
+ ### Aggregation & Data Processing
748
+ - [ ] Aggregation pipelines are optimized for sharded cluster pushdown
749
+ - [ ] Memory-intensive aggregations use allowDiskUse option when needed
750
+ - [ ] Pipeline stages are ordered for optimal performance
751
+ - [ ] Group operations use shard key fields when possible for better distribution
752
+ - [ ] Complex aggregations are broken into smaller, reusable pipeline stages
753
+ - [ ] Result size limitations are considered for large aggregation outputs
754
+
755
+ ### Security & Production Readiness
756
+ - [ ] Database credentials are stored securely and not hardcoded
757
+ - [ ] Input validation prevents NoSQL injection attacks
758
+ - [ ] Database user permissions follow principle of least privilege
759
+ - [ ] Sensitive data is encrypted at rest and in transit
760
+ - [ ] Database operations are logged appropriately for audit purposes
761
+ - [ ] Backup and recovery procedures are tested and documented