Skip to content

Blog

MongoDB Capped Collections and Circular Buffers: High-Performance Logging, Event Streaming, and Fixed-Size Data Management for High-Throughput Applications

High-throughput applications require specialized data storage patterns that can handle massive write volumes while maintaining predictable performance characteristics and managing storage space efficiently. Traditional relational database approaches to logging and event streaming often struggle with write scalability, storage growth management, and query performance under extreme load conditions, particularly when dealing with time-series data, application logs, and real-time event streams.

MongoDB's capped collections provide a unique solution for these scenarios, offering fixed-size collections that automatically maintain insertion order and efficiently manage storage by overwriting old documents when capacity limits are reached. Unlike traditional log rotation mechanisms that require complex external processes and can introduce performance bottlenecks, capped collections provide built-in circular buffer functionality with native MongoDB integration, tailable cursors for real-time streaming, and optimized write performance that makes them ideal for high-throughput logging, event processing, and time-sensitive data scenarios.

The Traditional High-Volume Logging Challenge

Conventional database approaches to high-volume logging and event streaming face significant scalability and management challenges:

-- Traditional PostgreSQL high-volume logging - storage growth and performance challenges

-- Application log table with typical structure
CREATE TABLE application_logs (
  log_id BIGSERIAL PRIMARY KEY,
  timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  application_name VARCHAR(100) NOT NULL,
  environment VARCHAR(20) DEFAULT 'production',
  log_level VARCHAR(10) NOT NULL, -- DEBUG, INFO, WARN, ERROR, FATAL
  message TEXT NOT NULL,
  user_id UUID,
  session_id VARCHAR(100),
  request_id VARCHAR(100),

  -- Contextual information
  source_ip INET,
  user_agent TEXT,
  request_method VARCHAR(10),
  request_url TEXT,
  response_status INTEGER,
  response_time_ms INTEGER,

  -- Structured data fields
  metadata JSONB,
  tags TEXT[],

  -- Performance tracking
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

  -- Indexing for queries
  CONSTRAINT valid_log_level CHECK (log_level IN ('DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL'))
);

-- Indexes for log querying (expensive to maintain with high write volume)
CREATE INDEX idx_application_logs_timestamp ON application_logs USING BTREE (timestamp DESC);
CREATE INDEX idx_application_logs_application ON application_logs (application_name, timestamp DESC);
CREATE INDEX idx_application_logs_level ON application_logs (log_level, timestamp DESC) WHERE log_level IN ('ERROR', 'FATAL');
CREATE INDEX idx_application_logs_user ON application_logs (user_id, timestamp DESC) WHERE user_id IS NOT NULL;
CREATE INDEX idx_application_logs_session ON application_logs (session_id, timestamp DESC) WHERE session_id IS NOT NULL;
CREATE INDEX idx_application_logs_request ON application_logs (request_id) WHERE request_id IS NOT NULL;

-- Partitioning strategy for managing large datasets (complex setup)
CREATE TABLE application_logs_y2024m01 PARTITION OF application_logs
FOR VALUES FROM ('2024-01-01') TO ('2024-02-01');

CREATE TABLE application_logs_y2024m02 PARTITION OF application_logs  
FOR VALUES FROM ('2024-02-01') TO ('2024-03-01');

CREATE TABLE application_logs_y2024m03 PARTITION OF application_logs
FOR VALUES FROM ('2024-03-01') TO ('2024-04-01');

-- Complex log rotation and cleanup procedures (operational overhead)
-- Daily log cleanup procedure
CREATE OR REPLACE FUNCTION cleanup_old_logs()
RETURNS void AS $$
DECLARE
  cutoff_date TIMESTAMP;
  affected_rows BIGINT;
  partition_name TEXT;
  partition_start DATE;
  partition_end DATE;
BEGIN
  -- Keep logs for 30 days
  cutoff_date := CURRENT_TIMESTAMP - INTERVAL '30 days';

  -- Delete old logs in batches to avoid lock contention
  LOOP
    DELETE FROM application_logs 
    WHERE timestamp < cutoff_date 
    AND log_id IN (
      SELECT log_id FROM application_logs 
      WHERE timestamp < cutoff_date 
      LIMIT 10000
    );

    GET DIAGNOSTICS affected_rows = ROW_COUNT;
    EXIT WHEN affected_rows = 0;

    -- Commit batch and pause to reduce system impact
    COMMIT;
    PERFORM pg_sleep(0.1);
  END LOOP;

  -- Drop old partitions if using partitioning
  FOR partition_name, partition_start, partition_end IN
    SELECT schemaname||'.'||tablename, 
           split_part(split_part(pg_get_expr(c.relpartbound, c.oid), '''', 2), '''', 1)::date,
           split_part(split_part(pg_get_expr(c.relpartbound, c.oid), '''', 4), '''', 1)::date
    FROM pg_tables pt
    JOIN pg_class c ON c.relname = pt.tablename
    WHERE pt.tablename LIKE 'application_logs_y%'
      AND split_part(split_part(pg_get_expr(c.relpartbound, c.oid), '''', 4), '''', 1)::date < CURRENT_DATE - INTERVAL '30 days'
  LOOP
    EXECUTE format('DROP TABLE IF EXISTS %s', partition_name);
  END LOOP;

END;
$$ LANGUAGE plpgsql;

-- Schedule daily cleanup (requires external scheduler)
-- 0 2 * * * /usr/bin/psql -d myapp -c "SELECT cleanup_old_logs();"

-- Complex high-volume log insertion with batching
WITH log_batch AS (
  INSERT INTO application_logs (
    application_name, environment, log_level, message, user_id, 
    session_id, request_id, source_ip, user_agent, request_method, 
    request_url, response_status, response_time_ms, metadata, tags
  ) VALUES 
  ('web-api', 'production', 'INFO', 'User login successful', 
   '550e8400-e29b-41d4-a716-446655440000', 'sess_abc123', 'req_xyz789',
   '192.168.1.100', 'Mozilla/5.0...', 'POST', '/api/auth/login', 200, 150,
   '{"login_method": "email", "ip_geolocation": "US-CA"}', ARRAY['auth', 'login']
  ),
  ('web-api', 'production', 'WARN', 'Rate limit threshold reached', 
   '550e8400-e29b-41d4-a716-446655440001', 'sess_def456', 'req_abc123',
   '192.168.1.101', 'PostmanRuntime/7.29.0', 'POST', '/api/data/upload', 429, 50,
   '{"rate_limit": "100_per_minute", "current_count": 101}', ARRAY['rate_limiting', 'api']
  ),
  ('background-worker', 'production', 'ERROR', 'Database connection timeout', 
   NULL, NULL, 'job_456789',
   NULL, NULL, NULL, NULL, NULL, 5000,
   '{"error_code": "DB_TIMEOUT", "retry_attempt": 3, "queue_size": 1500}', ARRAY['database', 'error', 'timeout']
  ),
  ('web-api', 'production', 'DEBUG', 'Cache miss for user preferences', 
   '550e8400-e29b-41d4-a716-446655440002', 'sess_ghi789', 'req_def456',
   '192.168.1.102', 'React Native App', 'GET', '/api/user/preferences', 200, 85,
   '{"cache_key": "user_prefs_12345", "cache_ttl": 300}', ARRAY['cache', 'performance']
  )
  RETURNING log_id, timestamp, application_name, log_level
)
SELECT 
  COUNT(*) as logs_inserted,
  MIN(timestamp) as first_log_time,
  MAX(timestamp) as last_log_time,
  string_agg(DISTINCT application_name, ', ') as applications,
  string_agg(DISTINCT log_level, ', ') as log_levels
FROM log_batch;

-- Complex log analysis queries (expensive on large datasets)
WITH hourly_log_stats AS (
  SELECT 
    date_trunc('hour', timestamp) as hour_bucket,
    application_name,
    log_level,
    COUNT(*) as log_count,

    -- Error rate calculation
    COUNT(*) FILTER (WHERE log_level IN ('ERROR', 'FATAL')) as error_count,
    COUNT(*) FILTER (WHERE log_level IN ('ERROR', 'FATAL'))::float / COUNT(*) * 100 as error_rate_percent,

    -- Response time statistics
    AVG(response_time_ms) FILTER (WHERE response_time_ms IS NOT NULL) as avg_response_time,
    PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY response_time_ms) FILTER (WHERE response_time_ms IS NOT NULL) as p95_response_time,

    -- Request statistics
    COUNT(DISTINCT user_id) FILTER (WHERE user_id IS NOT NULL) as unique_users,
    COUNT(DISTINCT session_id) FILTER (WHERE session_id IS NOT NULL) as unique_sessions,

    -- Top error messages
    mode() WITHIN GROUP (ORDER BY message) FILTER (WHERE log_level IN ('ERROR', 'FATAL')) as most_common_error,

    -- Resource utilization indicators
    COUNT(*) FILTER (WHERE response_time_ms > 1000) as slow_requests,
    COUNT(*) FILTER (WHERE response_status >= 400) as client_errors,
    COUNT(*) FILTER (WHERE response_status >= 500) as server_errors

  FROM application_logs
  WHERE timestamp >= CURRENT_TIMESTAMP - INTERVAL '24 hours'
    AND timestamp < CURRENT_TIMESTAMP
  GROUP BY date_trunc('hour', timestamp), application_name, log_level
),

trend_analysis AS (
  SELECT 
    hour_bucket,
    application_name,
    log_level,
    log_count,
    error_rate_percent,
    avg_response_time,

    -- Hour-over-hour trend analysis
    LAG(log_count) OVER (
      PARTITION BY application_name, log_level 
      ORDER BY hour_bucket
    ) as prev_hour_count,

    LAG(error_rate_percent) OVER (
      PARTITION BY application_name, log_level 
      ORDER BY hour_bucket
    ) as prev_hour_error_rate,

    LAG(avg_response_time) OVER (
      PARTITION BY application_name, log_level 
      ORDER BY hour_bucket
    ) as prev_hour_response_time,

    -- Calculate trends
    CASE 
      WHEN LAG(log_count) OVER (PARTITION BY application_name, log_level ORDER BY hour_bucket) IS NOT NULL THEN
        ((log_count - LAG(log_count) OVER (PARTITION BY application_name, log_level ORDER BY hour_bucket))::float / 
         LAG(log_count) OVER (PARTITION BY application_name, log_level ORDER BY hour_bucket) * 100)
      ELSE NULL
    END as log_count_change_percent,

    -- Moving averages
    AVG(log_count) OVER (
      PARTITION BY application_name, log_level 
      ORDER BY hour_bucket 
      ROWS BETWEEN 3 PRECEDING AND CURRENT ROW
    ) as rolling_4h_avg_count,

    AVG(error_rate_percent) OVER (
      PARTITION BY application_name, log_level 
      ORDER BY hour_bucket 
      ROWS BETWEEN 3 PRECEDING AND CURRENT ROW  
    ) as rolling_4h_avg_error_rate

  FROM hourly_log_stats
)

SELECT 
  hour_bucket,
  application_name,
  log_level,
  log_count,
  ROUND(error_rate_percent::numeric, 2) as error_rate_percent,
  ROUND(avg_response_time::numeric, 2) as avg_response_time_ms,

  -- Trend indicators
  ROUND(log_count_change_percent::numeric, 1) as hourly_change_percent,
  ROUND(rolling_4h_avg_count::numeric, 0) as rolling_4h_avg,
  ROUND(rolling_4h_avg_error_rate::numeric, 2) as rolling_4h_avg_error_rate,

  -- Alert conditions
  CASE 
    WHEN error_rate_percent > rolling_4h_avg_error_rate * 2 AND error_rate_percent > 1 THEN 'HIGH_ERROR_RATE'
    WHEN log_count_change_percent > 100 THEN 'TRAFFIC_SPIKE'
    WHEN log_count_change_percent < -50 AND log_count < rolling_4h_avg * 0.5 THEN 'TRAFFIC_DROP'
    WHEN avg_response_time > 1000 THEN 'HIGH_LATENCY'
    ELSE 'NORMAL'
  END as alert_condition,

  CURRENT_TIMESTAMP as analysis_time

FROM trend_analysis
ORDER BY hour_bucket DESC, application_name, log_level;

-- Problems with traditional PostgreSQL logging approaches:
-- 1. Unlimited storage growth requiring complex rotation strategies
-- 2. Index maintenance overhead degrading write performance
-- 3. Partitioning complexity for managing large datasets
-- 4. Expensive cleanup operations impacting production performance
-- 5. Limited real-time streaming capabilities for log analysis
-- 6. Complex batching logic required for high-volume insertions
-- 7. Vacuum and maintenance operations required for table health
-- 8. Query performance degradation as table size grows
-- 9. Storage space reclamation challenges after log deletion
-- 10. Manual operational overhead for log management and cleanup

-- Additional complications:
-- - WAL (Write-Ahead Log) bloat from high-volume insertions
-- - Lock contention during peak logging periods
-- - Backup complexity due to large log table sizes
-- - Replication lag caused by high write volume
-- - Statistics staleness affecting query plan optimization
-- - Complex monitoring required for log system health
-- - Difficulty implementing real-time log streaming
-- - Storage I/O bottlenecks during cleanup operations

MongoDB capped collections provide elegant solutions for high-volume logging:

// MongoDB Capped Collections - efficient high-volume logging with built-in circular buffer functionality
const { MongoClient } = require('mongodb');

const client = new MongoClient('mongodb://localhost:27017');
const db = client.db('high_throughput_logging_platform');

// Advanced MongoDB Capped Collections manager for high-performance logging and event streaming
class AdvancedCappedCollectionManager {
  constructor(db) {
    this.db = db;
    this.collections = new Map();
    this.tailable_cursors = new Map();
    this.streaming_handlers = new Map();

    // Configuration for different log types and use cases
    this.cappedConfigurations = {
      // Application logs with high write volume
      application_logs: {
        size: 1024 * 1024 * 1024, // 1GB
        max: 10000000, // 10 million documents
        indexing: ['timestamp', 'application', 'level'],
        streaming: true,
        compression: true,
        retention_hours: 72
      },

      // Real-time event stream
      event_stream: {
        size: 512 * 1024 * 1024, // 512MB
        max: 5000000, // 5 million events
        indexing: ['timestamp', 'event_type'],
        streaming: true,
        compression: false, // For lowest latency
        retention_hours: 24
      },

      // System metrics collection
      system_metrics: {
        size: 2048 * 1024 * 1024, // 2GB
        max: 20000000, // 20 million metrics
        indexing: ['timestamp', 'metric_type', 'host'],
        streaming: true,
        compression: true,
        retention_hours: 168 // 7 days
      },

      // User activity tracking
      user_activity: {
        size: 256 * 1024 * 1024, // 256MB
        max: 2000000, // 2 million activities
        indexing: ['timestamp', 'user_id', 'activity_type'],
        streaming: false,
        compression: true,
        retention_hours: 24
      },

      // Error and exception tracking
      error_logs: {
        size: 128 * 1024 * 1024, // 128MB
        max: 500000, // 500k errors
        indexing: ['timestamp', 'application', 'error_type', 'severity'],
        streaming: true,
        compression: false, // For immediate processing
        retention_hours: 168 // 7 days
      }
    };

    // Performance monitoring
    this.stats = {
      writes_per_second: new Map(),
      collection_sizes: new Map(),
      streaming_clients: new Map()
    };
  }

  async initializeCappedCollections() {
    console.log('Initializing advanced capped collections for high-throughput logging...');

    const initializationResults = [];

    for (const [collectionName, config] of Object.entries(this.cappedConfigurations)) {
      try {
        console.log(`Setting up capped collection: ${collectionName}`);

        // Create capped collection with optimal configuration
        const collection = await this.createOptimizedCappedCollection(collectionName, config);

        // Setup indexing strategy
        await this.setupCollectionIndexes(collection, config.indexing);

        // Initialize real-time streaming if enabled
        if (config.streaming) {
          await this.setupRealTimeStreaming(collectionName, collection);
        }

        // Setup monitoring and statistics
        await this.setupCollectionMonitoring(collectionName, collection, config);

        this.collections.set(collectionName, {
          collection: collection,
          config: config,
          created_at: new Date(),
          stats: {
            documents_written: 0,
            bytes_written: 0,
            last_write: null,
            streaming_clients: 0
          }
        });

        initializationResults.push({
          collection: collectionName,
          status: 'success',
          size_mb: Math.round(config.size / (1024 * 1024)),
          max_documents: config.max,
          streaming_enabled: config.streaming
        });

      } catch (error) {
        console.error(`Failed to initialize capped collection ${collectionName}:`, error);
        initializationResults.push({
          collection: collectionName,
          status: 'error',
          error: error.message
        });
      }
    }

    console.log(`Initialized ${initializationResults.filter(r => r.status === 'success').length} capped collections`);
    return initializationResults;
  }

  async createOptimizedCappedCollection(name, config) {
    console.log(`Creating capped collection '${name}' with ${Math.round(config.size / (1024 * 1024))}MB capacity`);

    try {
      // Check if collection already exists
      const existingCollections = await this.db.listCollections({ name: name }).toArray();

      if (existingCollections.length > 0) {
        const existing = existingCollections[0];

        if (existing.options?.capped) {
          console.log(`Capped collection '${name}' already exists`);
          return this.db.collection(name);
        } else {
          throw new Error(`Collection '${name}' exists but is not capped`);
        }
      }

      // Create new capped collection with optimized settings
      const createOptions = {
        capped: true,
        size: config.size,
        max: config.max
      };

      await this.db.createCollection(name, createOptions);
      const collection = this.db.collection(name);

      console.log(`Created capped collection '${name}' successfully`);
      return collection;

    } catch (error) {
      console.error(`Error creating capped collection '${name}':`, error);
      throw error;
    }
  }

  async setupCollectionIndexes(collection, indexFields) {
    console.log(`Setting up indexes for capped collection: ${collection.collectionName}`);

    try {
      // Create indexes for efficient querying (note: capped collections have limitations on indexing)
      const indexPromises = indexFields.map(async (field) => {
        const indexSpec = {};
        indexSpec[field] = 1;

        try {
          await collection.createIndex(indexSpec, { 
            background: true,
            name: `idx_${field}`
          });
          console.log(`Created index on field: ${field}`);
        } catch (error) {
          // Some indexes may not be supported on capped collections
          console.warn(`Could not create index on ${field}: ${error.message}`);
        }
      });

      await Promise.allSettled(indexPromises);

    } catch (error) {
      console.error(`Error setting up indexes for ${collection.collectionName}:`, error);
    }
  }

  async setupRealTimeStreaming(collectionName, collection) {
    console.log(`Setting up real-time streaming for: ${collectionName}`);

    try {
      // Create tailable cursor for real-time document streaming
      const tailableCursor = collection.find({}, {
        tailable: true,
        awaitData: true,
        noCursorTimeout: true,
        maxTimeMS: 0
      });

      this.tailable_cursors.set(collectionName, tailableCursor);

      // Setup streaming event handlers
      const streamingHandler = async (document) => {
        await this.processStreamingDocument(collectionName, document);
      };

      this.streaming_handlers.set(collectionName, streamingHandler);

      // Start streaming in background
      this.startTailableStreaming(collectionName, tailableCursor, streamingHandler);

      console.log(`Real-time streaming enabled for: ${collectionName}`);

    } catch (error) {
      console.error(`Error setting up streaming for ${collectionName}:`, error);
    }
  }

  async startTailableStreaming(collectionName, cursor, handler) {
    console.log(`Starting tailable streaming for: ${collectionName}`);

    try {
      // Process documents as they are inserted
      for await (const document of cursor) {
        try {
          await handler(document);
          this.updateStreamingStats(collectionName, 'document_streamed');
        } catch (error) {
          console.error(`Error processing streamed document in ${collectionName}:`, error);
          this.updateStreamingStats(collectionName, 'streaming_error');
        }
      }
    } catch (error) {
      console.error(`Tailable streaming error for ${collectionName}:`, error);

      // Attempt to restart streaming after delay
      setTimeout(() => {
        console.log(`Restarting tailable streaming for: ${collectionName}`);
        this.startTailableStreaming(collectionName, cursor, handler);
      }, 5000);
    }
  }

  async processStreamingDocument(collectionName, document) {
    // Process real-time document based on collection type
    switch (collectionName) {
      case 'application_logs':
        await this.processLogDocument(document);
        break;
      case 'event_stream':
        await this.processEventDocument(document);
        break;
      case 'system_metrics':
        await this.processMetricDocument(document);
        break;
      case 'error_logs':
        await this.processErrorDocument(document);
        break;
      default:
        console.log(`Streamed document from ${collectionName}:`, document._id);
    }
  }

  async processLogDocument(logDocument) {
    // Real-time log processing
    console.log(`Processing log: ${logDocument.level} - ${logDocument.application}`);

    // Alert on critical errors
    if (logDocument.level === 'ERROR' || logDocument.level === 'FATAL') {
      await this.triggerErrorAlert(logDocument);
    }

    // Update real-time metrics
    await this.updateLogMetrics(logDocument);
  }

  async processEventDocument(eventDocument) {
    // Real-time event processing
    console.log(`Processing event: ${eventDocument.event_type}`);

    // Update event counters
    await this.updateEventCounters(eventDocument);

    // Trigger event-based workflows
    if (eventDocument.event_type === 'user_purchase') {
      await this.triggerPurchaseWorkflow(eventDocument);
    }
  }

  async processMetricDocument(metricDocument) {
    // Real-time metrics processing
    console.log(`Processing metric: ${metricDocument.metric_type} = ${metricDocument.value}`);

    // Check thresholds
    if (metricDocument.metric_type === 'cpu_usage' && metricDocument.value > 80) {
      await this.triggerHighCPUAlert(metricDocument);
    }
  }

  async processErrorDocument(errorDocument) {
    // Real-time error processing
    console.log(`Processing error: ${errorDocument.error_type} in ${errorDocument.application}`);

    // Immediate alerting for critical errors
    if (errorDocument.severity === 'CRITICAL') {
      await this.triggerCriticalErrorAlert(errorDocument);
    }
  }

  async logEvent(collectionName, eventData, options = {}) {
    console.log(`Logging event to ${collectionName}`);

    try {
      const collectionData = this.collections.get(collectionName);
      if (!collectionData) {
        throw new Error(`Capped collection ${collectionName} not initialized`);
      }

      const collection = collectionData.collection;

      // Enhance event data with standard fields
      const enhancedEvent = {
        ...eventData,
        timestamp: new Date(),
        _logged_at: new Date(),
        _collection_type: collectionName,

        // Add metadata if specified
        ...(options.metadata && { _metadata: options.metadata }),

        // Add correlation ID for tracking
        ...(options.correlationId && { _correlation_id: options.correlationId })
      };

      // High-performance insert (no acknowledgment waiting for maximum throughput)
      const insertOptions = {
        writeConcern: options.writeConcern || { w: 0 }, // No acknowledgment for maximum speed
        ordered: false // Allow out-of-order inserts for better performance
      };

      const result = await collection.insertOne(enhancedEvent, insertOptions);

      // Update statistics
      this.updateWriteStats(collectionName, enhancedEvent);

      return {
        success: true,
        insertedId: result.insertedId,
        collection: collectionName,
        timestamp: enhancedEvent.timestamp
      };

    } catch (error) {
      console.error(`Error logging to ${collectionName}:`, error);

      // Update error statistics
      this.updateWriteStats(collectionName, null, error);

      throw error;
    }
  }

  async logEventBatch(collectionName, events, options = {}) {
    console.log(`Logging batch of ${events.length} events to ${collectionName}`);

    try {
      const collectionData = this.collections.get(collectionName);
      if (!collectionData) {
        throw new Error(`Capped collection ${collectionName} not initialized`);
      }

      const collection = collectionData.collection;
      const timestamp = new Date();

      // Enhance all events with standard fields
      const enhancedEvents = events.map((eventData, index) => ({
        ...eventData,
        timestamp: new Date(timestamp.getTime() + index), // Ensure unique timestamps
        _logged_at: timestamp,
        _collection_type: collectionName,
        _batch_id: options.batchId || require('crypto').randomUUID(),

        // Add metadata if specified
        ...(options.metadata && { _metadata: options.metadata })
      }));

      // High-performance batch insert
      const insertOptions = {
        writeConcern: options.writeConcern || { w: 0 }, // No acknowledgment
        ordered: false // Allow out-of-order inserts
      };

      const result = await collection.insertMany(enhancedEvents, insertOptions);

      // Update statistics for all events
      enhancedEvents.forEach(event => this.updateWriteStats(collectionName, event));

      return {
        success: true,
        insertedCount: result.insertedCount,
        insertedIds: result.insertedIds,
        collection: collectionName,
        batchSize: events.length,
        timestamp: timestamp
      };

    } catch (error) {
      console.error(`Error batch logging to ${collectionName}:`, error);

      // Update error statistics
      this.updateWriteStats(collectionName, null, error);

      throw error;
    }
  }

  async queryRecentEvents(collectionName, query = {}, options = {}) {
    console.log(`Querying recent events from ${collectionName}`);

    try {
      const collectionData = this.collections.get(collectionName);
      if (!collectionData) {
        throw new Error(`Capped collection ${collectionName} not initialized`);
      }

      const collection = collectionData.collection;

      // Build query with time-based filtering
      const timeFilter = {};
      if (options.since) {
        timeFilter.timestamp = { $gte: options.since };
      }
      if (options.until) {
        timeFilter.timestamp = { ...timeFilter.timestamp, $lte: options.until };
      }

      const finalQuery = {
        ...query,
        ...timeFilter
      };

      // Query options for efficient retrieval
      const queryOptions = {
        sort: options.sort || { $natural: -1 }, // Natural order for capped collections
        limit: options.limit || 1000,
        projection: options.projection || {}
      };

      const cursor = collection.find(finalQuery, queryOptions);
      const results = await cursor.toArray();

      console.log(`Retrieved ${results.length} events from ${collectionName}`);

      return {
        collection: collectionName,
        count: results.length,
        events: results,
        query: finalQuery,
        options: queryOptions
      };

    } catch (error) {
      console.error(`Error querying ${collectionName}:`, error);
      throw error;
    }
  }

  async getCollectionStats(collectionName) {
    console.log(`Getting statistics for capped collection: ${collectionName}`);

    try {
      const collectionData = this.collections.get(collectionName);
      if (!collectionData) {
        throw new Error(`Capped collection ${collectionName} not initialized`);
      }

      const collection = collectionData.collection;

      // Get collection statistics
      const stats = await this.db.command({ collStats: collectionName });
      const recentStats = collectionData.stats;

      // Calculate performance metrics
      const now = Date.now();
      const timeSinceLastWrite = recentStats.last_write ? 
        (now - recentStats.last_write.getTime()) / 1000 : null;

      const writesPerSecond = this.stats.writes_per_second.get(collectionName) || 0;

      return {
        collection_name: collectionName,

        // MongoDB collection stats
        is_capped: stats.capped,
        max_size: stats.maxSize,
        max_documents: stats.max,
        current_size: stats.size,
        storage_size: stats.storageSize,
        document_count: stats.count,
        average_document_size: stats.avgObjSize,

        // Usage statistics
        size_utilization_percent: (stats.size / stats.maxSize * 100).toFixed(2),
        document_utilization_percent: stats.max ? (stats.count / stats.max * 100).toFixed(2) : null,

        // Performance metrics
        writes_per_second: writesPerSecond,
        documents_written: recentStats.documents_written,
        bytes_written: recentStats.bytes_written,
        last_write: recentStats.last_write,
        time_since_last_write_seconds: timeSinceLastWrite,

        // Streaming statistics
        streaming_enabled: collectionData.config.streaming,
        streaming_clients: recentStats.streaming_clients,

        // Configuration
        retention_hours: collectionData.config.retention_hours,
        compression_enabled: collectionData.config.compression,

        // Timestamps
        created_at: collectionData.created_at,
        stats_generated_at: new Date()
      };

    } catch (error) {
      console.error(`Error getting stats for ${collectionName}:`, error);
      throw error;
    }
  }

  async getAllCollectionStats() {
    console.log('Getting comprehensive statistics for all capped collections');

    const allStats = {};
    const promises = Array.from(this.collections.keys()).map(async (collectionName) => {
      try {
        const stats = await this.getCollectionStats(collectionName);
        allStats[collectionName] = stats;
      } catch (error) {
        allStats[collectionName] = { error: error.message };
      }
    });

    await Promise.all(promises);

    // Calculate aggregate statistics
    const aggregateStats = {
      total_collections: Object.keys(allStats).length,
      total_documents: 0,
      total_size_bytes: 0,
      total_writes_per_second: 0,
      collections_with_streaming: 0,
      average_utilization_percent: 0
    };

    let validCollections = 0;
    for (const [name, stats] of Object.entries(allStats)) {
      if (!stats.error) {
        validCollections++;
        aggregateStats.total_documents += stats.document_count || 0;
        aggregateStats.total_size_bytes += stats.current_size || 0;
        aggregateStats.total_writes_per_second += stats.writes_per_second || 0;
        if (stats.streaming_enabled) aggregateStats.collections_with_streaming++;
        aggregateStats.average_utilization_percent += parseFloat(stats.size_utilization_percent) || 0;
      }
    }

    if (validCollections > 0) {
      aggregateStats.average_utilization_percent /= validCollections;
    }

    return {
      individual_collections: allStats,
      aggregate_statistics: aggregateStats,
      generated_at: new Date()
    };
  }

  // Real-time streaming client management
  createTailableStream(collectionName, filter = {}, options = {}) {
    console.log(`Creating tailable stream for: ${collectionName}`);

    const collectionData = this.collections.get(collectionName);
    if (!collectionData || !collectionData.config.streaming) {
      throw new Error(`Collection ${collectionName} is not configured for streaming`);
    }

    const collection = collectionData.collection;

    // Create tailable cursor with real-time options
    const tailableOptions = {
      tailable: true,
      awaitData: true,
      noCursorTimeout: true,
      maxTimeMS: 0,
      ...options
    };

    const cursor = collection.find(filter, tailableOptions);

    // Update streaming client count
    this.updateStreamingStats(collectionName, 'client_connected');

    return cursor;
  }

  // Utility methods for statistics and monitoring
  updateWriteStats(collectionName, eventData, error = null) {
    const collectionData = this.collections.get(collectionName);
    if (!collectionData) return;

    if (error) {
      // Handle error statistics
      collectionData.stats.errors = (collectionData.stats.errors || 0) + 1;
    } else {
      // Update write statistics
      collectionData.stats.documents_written++;
      collectionData.stats.last_write = new Date();

      if (eventData) {
        const eventSize = JSON.stringify(eventData).length;
        collectionData.stats.bytes_written += eventSize;
      }
    }

    // Update writes per second
    this.updateWritesPerSecond(collectionName);
  }

  updateWritesPerSecond(collectionName) {
    const now = Date.now();
    const key = `${collectionName}_${Math.floor(now / 1000)}`;

    if (!this.stats.writes_per_second.has(collectionName)) {
      this.stats.writes_per_second.set(collectionName, 0);
    }

    // Simple writes per second calculation
    this.stats.writes_per_second.set(
      collectionName, 
      this.stats.writes_per_second.get(collectionName) + 1
    );

    // Reset counter every second
    setTimeout(() => {
      this.stats.writes_per_second.set(collectionName, 0);
    }, 1000);
  }

  updateStreamingStats(collectionName, action) {
    const collectionData = this.collections.get(collectionName);
    if (!collectionData) return;

    switch (action) {
      case 'client_connected':
        collectionData.stats.streaming_clients++;
        break;
      case 'client_disconnected':
        collectionData.stats.streaming_clients = Math.max(0, collectionData.stats.streaming_clients - 1);
        break;
      case 'document_streamed':
        collectionData.stats.documents_streamed = (collectionData.stats.documents_streamed || 0) + 1;
        break;
      case 'streaming_error':
        collectionData.stats.streaming_errors = (collectionData.stats.streaming_errors || 0) + 1;
        break;
    }
  }

  // Alert and notification methods
  async triggerErrorAlert(logDocument) {
    console.log(`🚨 ERROR ALERT: ${logDocument.application} - ${logDocument.message}`);
    // Implement alerting logic (email, Slack, PagerDuty, etc.)
  }

  async triggerCriticalErrorAlert(errorDocument) {
    console.log(`🔥 CRITICAL ERROR: ${errorDocument.application} - ${errorDocument.error_type}`);
    // Implement critical alerting logic
  }

  async triggerHighCPUAlert(metricDocument) {
    console.log(`⚠️ HIGH CPU: ${metricDocument.host} - ${metricDocument.value}%`);
    // Implement system monitoring alerts
  }

  // Workflow triggers
  async triggerPurchaseWorkflow(eventDocument) {
    console.log(`💰 Purchase Event: User ${eventDocument.user_id} - Amount ${eventDocument.amount}`);
    // Implement purchase-related workflows
  }

  // Metrics updating methods
  async updateLogMetrics(logDocument) {
    // Update aggregated log metrics in real-time
    const metricsUpdate = {
      $inc: {
        [`hourly_logs.${new Date().getHours()}.${logDocument.level.toLowerCase()}`]: 1,
        [`application_logs.${logDocument.application}.${logDocument.level.toLowerCase()}`]: 1
      },
      $set: {
        last_updated: new Date()
      }
    };

    await this.db.collection('log_metrics').updateOne(
      { _id: 'real_time_metrics' },
      metricsUpdate,
      { upsert: true }
    );
  }

  async updateEventCounters(eventDocument) {
    // Update real-time event counters
    const counterUpdate = {
      $inc: {
        [`event_counts.${eventDocument.event_type}`]: 1,
        'total_events': 1
      },
      $set: {
        last_event: new Date(),
        last_event_type: eventDocument.event_type
      }
    };

    await this.db.collection('event_metrics').updateOne(
      { _id: 'real_time_counters' },
      counterUpdate,
      { upsert: true }
    );
  }

  async setupCollectionMonitoring(collectionName, collection, config) {
    // Setup monitoring for collection health and performance
    setInterval(async () => {
      try {
        const stats = await this.getCollectionStats(collectionName);

        // Check for potential issues
        if (stats.size_utilization_percent > 90) {
          console.warn(`⚠️ Collection ${collectionName} is ${stats.size_utilization_percent}% full`);
        }

        if (stats.writes_per_second === 0 && config.retention_hours < 24) {
          console.warn(`⚠️ No recent writes to ${collectionName}`);
        }

      } catch (error) {
        console.error(`Error monitoring ${collectionName}:`, error);
      }
    }, 60000); // Check every minute
  }
}

// Example usage: High-performance logging system setup
async function setupHighPerformanceLogging() {
  console.log('Setting up comprehensive high-performance logging system with capped collections...');

  const cappedManager = new AdvancedCappedCollectionManager(db);

  // Initialize all capped collections
  await cappedManager.initializeCappedCollections();

  // Example: High-volume application logging
  const logEntries = [
    {
      application: 'web-api',
      level: 'INFO',
      message: 'User authentication successful',
      user_id: '507f1f77bcf86cd799439011',
      session_id: 'sess_abc123',
      request_id: 'req_xyz789',
      source_ip: '192.168.1.100',
      user_agent: 'Mozilla/5.0...',
      request_method: 'POST',
      request_url: '/api/auth/login',
      response_status: 200,
      response_time_ms: 150,
      metadata: {
        login_method: 'email',
        ip_geolocation: 'US-CA',
        device_type: 'desktop'
      }
    },
    {
      application: 'background-worker',
      level: 'ERROR',
      message: 'Database connection timeout',
      error_type: 'DatabaseTimeout',
      error_code: 'DB_CONN_TIMEOUT',
      stack_trace: 'Error: Connection timeout...',
      job_id: 'job_456789',
      queue_name: 'high_priority',
      retry_attempt: 3,
      metadata: {
        connection_pool_size: 10,
        active_connections: 9,
        queue_size: 1500
      }
    },
    {
      application: 'payment-service',
      level: 'WARN',
      message: 'Payment processing took longer than expected',
      user_id: '507f1f77bcf86cd799439012',
      transaction_id: 'txn_abc456',
      payment_method: 'credit_card',
      amount: 99.99,
      currency: 'USD',
      processing_time_ms: 5500,
      metadata: {
        gateway: 'stripe',
        gateway_response_time: 4800,
        fraud_check_time: 700
      }
    }
  ];

  // Batch insert logs for maximum performance
  await cappedManager.logEventBatch('application_logs', logEntries, {
    batchId: 'batch_001',
    metadata: { source: 'demo', environment: 'production' }
  });

  // Example: Real-time event streaming
  const events = [
    {
      event_type: 'user_signup',
      user_id: '507f1f77bcf86cd799439013',
      email: '[email protected]',
      signup_method: 'google_oauth',
      referrer: 'organic_search',
      metadata: {
        utm_source: 'google',
        utm_medium: 'organic',
        landing_page: '/pricing'
      }
    },
    {
      event_type: 'user_purchase',
      user_id: '507f1f77bcf86cd799439013',
      order_id: '507f1f77bcf86cd799439014',
      amount: 299.99,
      currency: 'USD',
      product_ids: ['prod_001', 'prod_002'],
      payment_method: 'stripe',
      metadata: {
        discount_applied: 50.00,
        coupon_code: 'SAVE50',
        affiliate_id: 'aff_123'
      }
    }
  ];

  await cappedManager.logEventBatch('event_stream', events);

  // Example: System metrics collection
  const metrics = [
    {
      metric_type: 'cpu_usage',
      host: 'web-server-01',
      value: 78.5,
      unit: 'percent',
      tags: ['production', 'web-tier']
    },
    {
      metric_type: 'memory_usage',
      host: 'web-server-01', 
      value: 6.2,
      unit: 'gb',
      tags: ['production', 'web-tier']
    },
    {
      metric_type: 'disk_io',
      host: 'db-server-01',
      value: 1250,
      unit: 'ops_per_second',
      tags: ['production', 'database-tier']
    }
  ];

  await cappedManager.logEventBatch('system_metrics', metrics);

  // Query recent events
  const recentErrors = await cappedManager.queryRecentEvents('error_logs', 
    { level: 'ERROR' }, 
    { limit: 100, since: new Date(Date.now() - 60 * 60 * 1000) } // Last hour
  );

  console.log(`Found ${recentErrors.count} recent errors`);

  // Get comprehensive statistics
  const stats = await cappedManager.getAllCollectionStats();
  console.log('Capped Collections System Status:', JSON.stringify(stats.aggregate_statistics, null, 2));

  // Setup real-time streaming
  const logStream = cappedManager.createTailableStream('application_logs', 
    { level: { $in: ['ERROR', 'FATAL'] } }
  );

  console.log('Real-time error log streaming started...');

  return cappedManager;
}

// Benefits of MongoDB Capped Collections:
// - Fixed-size collections with automatic space management
// - Built-in circular buffer functionality for efficient storage utilization
// - Optimized for high-throughput write operations with minimal overhead
// - Tailable cursors for real-time streaming and event processing
// - Natural insertion order preservation without additional indexing
// - No fragmentation issues compared to traditional log rotation
// - Automatic old document removal without manual cleanup processes
// - Superior performance for append-only workloads like logging
// - Built-in MongoDB integration with replication and sharding support
// - SQL-compatible operations through QueryLeaf for familiar management

module.exports = {
  AdvancedCappedCollectionManager,
  setupHighPerformanceLogging
};

Understanding MongoDB Capped Collections Architecture

Advanced Circular Buffer Implementation and High-Throughput Patterns

Implement sophisticated capped collection patterns for production-scale logging systems:

// Production-grade capped collection patterns for enterprise logging infrastructure
class EnterpriseCappedCollectionManager extends AdvancedCappedCollectionManager {
  constructor(db, enterpriseConfig) {
    super(db);

    this.enterpriseConfig = {
      multiTenant: enterpriseConfig.multiTenant || false,
      distributedLogging: enterpriseConfig.distributedLogging || false,
      compressionEnabled: enterpriseConfig.compressionEnabled || true,
      retentionPolicies: enterpriseConfig.retentionPolicies || {},
      alertingIntegration: enterpriseConfig.alertingIntegration || {},
      metricsExport: enterpriseConfig.metricsExport || {}
    };

    this.setupEnterpriseIntegrations();
  }

  async setupMultiTenantCappedCollections(tenants) {
    console.log('Setting up multi-tenant capped collection architecture...');

    const tenantCollections = new Map();

    for (const [tenantId, tenantConfig] of Object.entries(tenants)) {
      const tenantCollectionName = `logs_tenant_${tenantId}`;

      // Create tenant-specific capped collection
      const cappedConfig = {
        size: tenantConfig.logQuotaBytes || 128 * 1024 * 1024, // 128MB default
        max: tenantConfig.maxDocuments || 1000000,
        indexing: ['timestamp', 'level', 'application'],
        streaming: tenantConfig.streamingEnabled || false,
        compression: true,
        retention_hours: tenantConfig.retentionHours || 72
      };

      this.cappedConfigurations[tenantCollectionName] = cappedConfig;
      tenantCollections.set(tenantId, tenantCollectionName);
    }

    await this.initializeCappedCollections();
    return tenantCollections;
  }

  async setupDistributedLoggingAggregation(nodeConfigs) {
    console.log('Setting up distributed logging aggregation...');

    const aggregationStreams = {};

    for (const [nodeId, nodeConfig] of Object.entries(nodeConfigs)) {
      // Create aggregation stream for each distributed node
      aggregationStreams[`node_${nodeId}_aggregation`] = {
        sourceCollections: nodeConfig.sourceCollections,
        aggregationPipeline: [
          {
            $match: {
              timestamp: { $gte: new Date(Date.now() - 60000) }, // Last minute
              node_id: nodeId
            }
          },
          {
            $group: {
              _id: {
                minute: { $dateToString: { format: "%Y-%m-%d %H:%M", date: "$timestamp" } },
                level: "$level",
                application: "$application"
              },
              count: { $sum: 1 },
              first_occurrence: { $min: "$timestamp" },
              last_occurrence: { $max: "$timestamp" },
              sample_message: { $first: "$message" }
            }
          }
        ],
        targetCollection: `distributed_log_summary`,
        refreshInterval: 60000 // 1 minute
      };
    }

    return await this.implementAggregationStreams(aggregationStreams);
  }

  async setupLogRetentionPolicies(policies) {
    console.log('Setting up automated log retention policies...');

    const retentionTasks = {};

    for (const [collectionName, policy] of Object.entries(policies)) {
      retentionTasks[collectionName] = {
        retentionDays: policy.retentionDays,
        archiveToS3: policy.archiveToS3 || false,
        compressionLevel: policy.compressionLevel || 'standard',
        schedule: policy.schedule || '0 2 * * *', // Daily at 2 AM

        cleanupFunction: async () => {
          await this.executeRetentionPolicy(collectionName, policy);
        }
      };
    }

    return await this.scheduleRetentionTasks(retentionTasks);
  }

  async implementAdvancedStreaming(streamingConfigs) {
    console.log('Implementing advanced streaming capabilities...');

    const streamingServices = {};

    for (const [streamName, config] of Object.entries(streamingConfigs)) {
      streamingServices[streamName] = {
        sourceCollection: config.sourceCollection,
        filterPipeline: config.filterPipeline,
        transformFunction: config.transformFunction,
        destinations: config.destinations, // Kafka, Redis, WebSockets, etc.
        bufferSize: config.bufferSize || 1000,
        flushInterval: config.flushInterval || 1000,

        processor: async (documents) => {
          await this.processStreamingBatch(streamName, documents, config);
        }
      };
    }

    return await this.activateStreamingServices(streamingServices);
  }
}

SQL-Style Capped Collection Management with QueryLeaf

QueryLeaf provides familiar SQL syntax for MongoDB capped collection operations and management:

-- QueryLeaf capped collection management with SQL-familiar syntax

-- Create high-performance capped collection for application logging
CREATE CAPPED COLLECTION application_logs (
  size = '1GB',
  max_documents = 10000000,

  -- Document structure (for documentation)
  timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  application VARCHAR(100) NOT NULL,
  environment VARCHAR(20) DEFAULT 'production',
  level VARCHAR(10) NOT NULL CHECK (level IN ('DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL')),
  message TEXT NOT NULL,
  user_id UUID,
  session_id VARCHAR(100),
  request_id VARCHAR(100),

  -- Performance and context fields
  source_ip INET,
  user_agent TEXT,
  request_method VARCHAR(10),
  request_url TEXT,
  response_status INTEGER,
  response_time_ms INTEGER,

  -- Flexible metadata
  metadata JSONB,
  tags TEXT[]
)
WITH OPTIONS (
  write_concern = { w: 0 }, -- Maximum write performance
  tailable_cursors = true,  -- Enable real-time streaming
  compression = true,       -- Enable document compression
  streaming_enabled = true
);

-- Create real-time event stream capped collection
CREATE CAPPED COLLECTION event_stream (
  size = '512MB',
  max_documents = 5000000,

  -- Event structure
  event_type VARCHAR(100) NOT NULL,
  user_id UUID,
  session_id VARCHAR(100),
  event_data JSONB,

  -- Event context
  timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  source VARCHAR(50),
  environment VARCHAR(20),

  -- Event metadata
  correlation_id UUID,
  trace_id UUID,
  metadata JSONB
)
WITH OPTIONS (
  write_concern = { w: 0 },
  tailable_cursors = true,
  compression = false, -- Low latency over storage efficiency
  streaming_enabled = true,
  retention_hours = 24
);

-- Create system metrics capped collection
CREATE CAPPED COLLECTION system_metrics (
  size = '2GB', 
  max_documents = 20000000,

  -- Metrics structure
  metric_type VARCHAR(100) NOT NULL,
  host VARCHAR(100) NOT NULL,
  value DECIMAL(15,6) NOT NULL,
  unit VARCHAR(20),
  tags TEXT[],

  -- Timing information
  timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  collected_at TIMESTAMP,

  -- Metric metadata
  labels JSONB,
  metadata JSONB
)
WITH OPTIONS (
  write_concern = { w: 0 },
  tailable_cursors = true,
  compression = true,
  streaming_enabled = true,
  retention_hours = 168 -- 7 days
);

-- High-volume log insertion with optimized batch processing
INSERT INTO application_logs (
  application, environment, level, message, user_id, session_id, 
  request_id, source_ip, user_agent, request_method, request_url, 
  response_status, response_time_ms, metadata, tags
) VALUES 
-- Batch insert for maximum throughput
('web-api', 'production', 'INFO', 'User login successful', 
 '550e8400-e29b-41d4-a716-446655440000', 'sess_abc123', 'req_xyz789',
 '192.168.1.100', 'Mozilla/5.0...', 'POST', '/api/auth/login', 200, 150,
 JSON_OBJECT('login_method', 'email', 'ip_geolocation', 'US-CA', 'device_type', 'desktop'),
 ARRAY['authentication', 'user_activity']
),
('payment-service', 'production', 'WARN', 'Payment processing delay detected', 
 '550e8400-e29b-41d4-a716-446655440001', 'sess_def456', 'req_abc123',
 '192.168.1.101', 'Mobile App/1.2.3', 'POST', '/api/payments/process', 200, 3500,
 JSON_OBJECT('gateway', 'stripe', 'amount', 99.99, 'currency', 'USD', 'delay_reason', 'gateway_latency'),
 ARRAY['payments', 'performance', 'warning']
),
('background-worker', 'production', 'ERROR', 'Queue processing failure', 
 NULL, NULL, 'job_456789',
 NULL, NULL, NULL, NULL, NULL, NULL,
 JSON_OBJECT('queue_name', 'high_priority', 'job_type', 'email_sender', 'error_code', 'SMTP_TIMEOUT', 'retry_count', 3),
 ARRAY['background_job', 'error', 'email']
),
('web-api', 'production', 'DEBUG', 'Cache hit for user preferences', 
 '550e8400-e29b-41d4-a716-446655440002', 'sess_ghi789', 'req_def456',
 '192.168.1.102', 'React Native/1.0.0', 'GET', '/api/user/preferences', 200, 25,
 JSON_OBJECT('cache_key', 'user_prefs_12345', 'cache_ttl', 3600, 'hit_rate', 0.85),
 ARRAY['cache', 'performance', 'optimization']
)
WITH WRITE_OPTIONS (
  acknowledge = false,  -- No write acknowledgment for maximum throughput
  ordered = false,     -- Allow out-of-order inserts
  batch_size = 1000    -- Optimize batch size
);

-- Real-time event streaming insertion
INSERT INTO event_stream (
  event_type, user_id, session_id, event_data, source, 
  environment, correlation_id, trace_id, metadata
) VALUES 
('user_signup', '550e8400-e29b-41d4-a716-446655440003', 'sess_new123',
 JSON_OBJECT('email', '[email protected]', 'signup_method', 'google_oauth', 'referrer', 'organic_search'),
 'web-application', 'production', UUID(), UUID(),
 JSON_OBJECT('utm_source', 'google', 'utm_medium', 'organic', 'landing_page', '/pricing')
),
('purchase_completed', '550e8400-e29b-41d4-a716-446655440003', 'sess_new123',
 JSON_OBJECT('order_id', '550e8400-e29b-41d4-a716-446655440004', 'amount', 299.99, 'currency', 'USD', 'items', 2),
 'web-application', 'production', UUID(), UUID(),
 JSON_OBJECT('payment_method', 'stripe', 'discount_applied', 50.00, 'coupon_code', 'SAVE50')
),
('api_call', '550e8400-e29b-41d4-a716-446655440005', 'sess_api789',
 JSON_OBJECT('endpoint', '/api/data/export', 'method', 'GET', 'response_size_bytes', 1048576),
 'mobile-app', 'production', UUID(), UUID(),
 JSON_OBJECT('app_version', '2.1.0', 'os', 'iOS', 'device_model', 'iPhone13')
);

-- System metrics batch insertion
INSERT INTO system_metrics (
  metric_type, host, value, unit, tags, collected_at, labels, metadata
) VALUES 
('cpu_usage', 'web-server-01', 78.5, 'percent', ARRAY['production', 'web-tier'], CURRENT_TIMESTAMP,
 JSON_OBJECT('instance_type', 'm5.large', 'az', 'us-east-1a'),
 JSON_OBJECT('cores', 2, 'architecture', 'x86_64')
),
('memory_usage', 'web-server-01', 6.2, 'gb', ARRAY['production', 'web-tier'], CURRENT_TIMESTAMP,
 JSON_OBJECT('total_memory', '8gb', 'instance_type', 'm5.large'),
 JSON_OBJECT('swap_usage', '0.1gb', 'buffer_cache', '1.2gb')
),
('disk_io_read', 'db-server-01', 1250, 'ops_per_second', ARRAY['production', 'database-tier'], CURRENT_TIMESTAMP,
 JSON_OBJECT('disk_type', 'ssd', 'size', '500gb'),
 JSON_OBJECT('queue_depth', 32, 'utilization', 0.85)
),
('network_throughput', 'web-server-01', 45.8, 'mbps', ARRAY['production', 'web-tier'], CURRENT_TIMESTAMP,
 JSON_OBJECT('interface', 'eth0', 'max_bandwidth', '1000mbps'),
 JSON_OBJECT('packets_per_second', 15000, 'error_rate', 0.001)
);

-- Advanced querying with natural ordering (capped collections maintain insertion order)
SELECT 
  timestamp,
  application,
  level,
  message,
  user_id,
  request_id,
  response_time_ms,

  -- Extract specific metadata fields
  JSON_EXTRACT(metadata, '$.login_method') as login_method,
  JSON_EXTRACT(metadata, '$.error_code') as error_code,
  JSON_EXTRACT(metadata, '$.gateway') as payment_gateway,

  -- Categorize response times
  CASE 
    WHEN response_time_ms IS NULL THEN 'N/A'
    WHEN response_time_ms <= 100 THEN 'fast'
    WHEN response_time_ms <= 500 THEN 'acceptable' 
    WHEN response_time_ms <= 2000 THEN 'slow'
    ELSE 'very_slow'
  END as performance_category,

  -- Extract tags as comma-separated string
  ARRAY_TO_STRING(tags, ', ') as tag_list

FROM application_logs
WHERE 
  -- Query recent logs (capped collections are optimized for recent data)
  timestamp >= CURRENT_TIMESTAMP - INTERVAL '1 hour'

  -- Filter by log level
  AND level IN ('ERROR', 'WARN', 'FATAL')

  -- Filter by application
  AND application IN ('web-api', 'payment-service', 'background-worker')

  -- Filter by performance issues
  AND (response_time_ms > 1000 OR level = 'ERROR')

ORDER BY 
  -- Natural order is most efficient for capped collections
  timestamp DESC

LIMIT 1000;

-- Real-time streaming query with tailable cursor
SELECT 
  event_type,
  user_id,
  session_id,
  timestamp,

  -- Extract event-specific data
  JSON_EXTRACT(event_data, '$.email') as user_email,
  JSON_EXTRACT(event_data, '$.amount') as transaction_amount,
  JSON_EXTRACT(event_data, '$.order_id') as order_id,
  JSON_EXTRACT(event_data, '$.endpoint') as api_endpoint,

  -- Extract metadata
  JSON_EXTRACT(metadata, '$.utm_source') as traffic_source,
  JSON_EXTRACT(metadata, '$.payment_method') as payment_method,
  JSON_EXTRACT(metadata, '$.app_version') as app_version,

  -- Event categorization
  CASE 
    WHEN event_type LIKE '%signup%' THEN 'user_acquisition'
    WHEN event_type LIKE '%purchase%' THEN 'monetization'
    WHEN event_type LIKE '%api%' THEN 'api_usage'
    ELSE 'other'
  END as event_category

FROM event_stream
WHERE 
  -- Real-time event processing (last few minutes)
  timestamp >= CURRENT_TIMESTAMP - INTERVAL '5 minutes'

  -- Focus on high-value events
  AND (
    event_type IN ('user_signup', 'purchase_completed', 'subscription_upgraded')
    OR JSON_EXTRACT(event_data, '$.amount')::DECIMAL > 100
  )

ORDER BY timestamp DESC

-- Enable tailable cursor for real-time streaming
WITH CURSOR_OPTIONS (
  tailable = true,
  await_data = true,
  no_cursor_timeout = true
);

-- Aggregated metrics analysis from system_metrics capped collection
WITH recent_metrics AS (
  SELECT 
    metric_type,
    host,
    value,
    unit,
    timestamp,
    JSON_EXTRACT(labels, '$.instance_type') as instance_type,
    JSON_EXTRACT(labels, '$.az') as availability_zone,

    -- Time bucketing for aggregation
    DATE_TRUNC('minute', timestamp) as minute_bucket

  FROM system_metrics
  WHERE timestamp >= CURRENT_TIMESTAMP - INTERVAL '30 minutes'
),

aggregated_metrics AS (
  SELECT 
    minute_bucket,
    metric_type,
    host,
    instance_type,
    availability_zone,

    -- Statistical aggregations
    COUNT(*) as sample_count,
    AVG(value) as avg_value,
    MIN(value) as min_value,
    MAX(value) as max_value,
    STDDEV(value) as stddev_value,

    -- Percentile calculations
    PERCENTILE_CONT(0.50) WITHIN GROUP (ORDER BY value) as p50_value,
    PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY value) as p95_value,
    PERCENTILE_CONT(0.99) WITHIN GROUP (ORDER BY value) as p99_value,

    -- Trend analysis
    value - LAG(AVG(value)) OVER (
      PARTITION BY metric_type, host 
      ORDER BY minute_bucket
    ) as change_from_previous,

    -- Moving averages
    AVG(AVG(value)) OVER (
      PARTITION BY metric_type, host 
      ORDER BY minute_bucket 
      ROWS BETWEEN 4 PRECEDING AND CURRENT ROW
    ) as rolling_5min_avg

  FROM recent_metrics
  GROUP BY minute_bucket, metric_type, host, instance_type, availability_zone
)

SELECT 
  minute_bucket,
  metric_type,
  host,
  instance_type,
  availability_zone,

  -- Formatted metrics
  ROUND(avg_value::NUMERIC, 2) as avg_value,
  ROUND(p95_value::NUMERIC, 2) as p95_value,
  ROUND(rolling_5min_avg::NUMERIC, 2) as rolling_avg,

  -- Alert conditions
  CASE 
    WHEN metric_type = 'cpu_usage' AND avg_value > 80 THEN 'HIGH_CPU'
    WHEN metric_type = 'memory_usage' AND avg_value > 7 THEN 'HIGH_MEMORY'  
    WHEN metric_type = 'disk_io_read' AND avg_value > 2000 THEN 'HIGH_DISK_IO'
    WHEN metric_type = 'network_throughput' AND avg_value > 800 THEN 'HIGH_NETWORK'
    ELSE 'NORMAL'
  END as alert_status,

  -- Trend indicators
  CASE 
    WHEN change_from_previous > rolling_5min_avg * 0.2 THEN 'INCREASING'
    WHEN change_from_previous < rolling_5min_avg * -0.2 THEN 'DECREASING'
    ELSE 'STABLE'
  END as trend,

  sample_count,
  CURRENT_TIMESTAMP as analysis_time

FROM aggregated_metrics
ORDER BY minute_bucket DESC, metric_type, host;

-- Capped collection maintenance and monitoring
SELECT 
  collection_name,
  is_capped,
  max_size_bytes,
  max_documents,
  current_size_bytes,
  current_document_count,

  -- Utilization calculations
  ROUND((current_size_bytes::FLOAT / max_size_bytes * 100)::NUMERIC, 2) as size_utilization_percent,
  ROUND((current_document_count::FLOAT / max_documents * 100)::NUMERIC, 2) as document_utilization_percent,

  -- Efficiency metrics
  ROUND((current_size_bytes::FLOAT / current_document_count)::NUMERIC, 0) as avg_document_size_bytes,

  -- Storage projections
  CASE 
    WHEN size_utilization_percent > 90 THEN 'NEAR_CAPACITY'
    WHEN size_utilization_percent > 75 THEN 'HIGH_UTILIZATION'
    WHEN size_utilization_percent > 50 THEN 'MODERATE_UTILIZATION'  
    ELSE 'LOW_UTILIZATION'
  END as capacity_status,

  -- Recommendations
  CASE 
    WHEN size_utilization_percent > 95 THEN 'Consider increasing collection size'
    WHEN document_utilization_percent > 95 THEN 'Consider increasing max document limit'
    WHEN size_utilization_percent < 25 AND current_document_count > 1000 THEN 'Collection may be over-provisioned'
    ELSE 'Optimal configuration'
  END as recommendation

FROM INFORMATION_SCHEMA.CAPPED_COLLECTIONS
WHERE collection_name IN ('application_logs', 'event_stream', 'system_metrics')
ORDER BY size_utilization_percent DESC;

-- Real-time log analysis with streaming aggregation
CREATE STREAMING VIEW log_error_rates AS
SELECT 
  application,
  level,
  DATE_TRUNC('minute', timestamp) as minute_bucket,

  -- Error rate calculations
  COUNT(*) as total_logs,
  COUNT(*) FILTER (WHERE level IN ('ERROR', 'FATAL')) as error_count,
  ROUND(
    (COUNT(*) FILTER (WHERE level IN ('ERROR', 'FATAL'))::FLOAT / COUNT(*) * 100)::NUMERIC, 
    2
  ) as error_rate_percent,

  -- Performance metrics  
  AVG(response_time_ms) FILTER (WHERE response_time_ms IS NOT NULL) as avg_response_time,
  PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY response_time_ms) FILTER (WHERE response_time_ms IS NOT NULL) as p95_response_time,

  -- Request analysis
  COUNT(DISTINCT user_id) FILTER (WHERE user_id IS NOT NULL) as unique_users,
  COUNT(DISTINCT session_id) FILTER (WHERE session_id IS NOT NULL) as unique_sessions,

  -- Status code distribution
  COUNT(*) FILTER (WHERE response_status BETWEEN 200 AND 299) as success_count,
  COUNT(*) FILTER (WHERE response_status BETWEEN 400 AND 499) as client_error_count,
  COUNT(*) FILTER (WHERE response_status BETWEEN 500 AND 599) as server_error_count,

  CURRENT_TIMESTAMP as computed_at

FROM application_logs
WHERE timestamp >= CURRENT_TIMESTAMP - INTERVAL '5 minutes'
GROUP BY application, level, minute_bucket
WITH REFRESH INTERVAL 30 SECONDS;

-- Cleanup and maintenance operations for capped collections
-- Note: Capped collections automatically manage space, but monitoring is still important

-- Monitor capped collection health
WITH collection_health AS (
  SELECT 
    'application_logs' as collection_name,
    COUNT(*) as current_documents,
    MIN(timestamp) as oldest_document,
    MAX(timestamp) as newest_document,
    MAX(timestamp) - MIN(timestamp) as time_span,
    AVG(LENGTH(CAST(message AS TEXT))) as avg_message_length
  FROM application_logs

  UNION ALL

  SELECT 
    'event_stream' as collection_name,
    COUNT(*) as current_documents,
    MIN(timestamp) as oldest_document, 
    MAX(timestamp) as newest_document,
    MAX(timestamp) - MIN(timestamp) as time_span,
    AVG(LENGTH(CAST(event_data AS TEXT))) as avg_event_size
  FROM event_stream

  UNION ALL

  SELECT 
    'system_metrics' as collection_name,
    COUNT(*) as current_documents,
    MIN(timestamp) as oldest_document,
    MAX(timestamp) as newest_document, 
    MAX(timestamp) - MIN(timestamp) as time_span,
    AVG(LENGTH(CAST(labels AS TEXT))) as avg_label_size
  FROM system_metrics
)

SELECT 
  collection_name,
  current_documents,
  oldest_document,
  newest_document,

  -- Time span analysis
  EXTRACT(DAYS FROM time_span) as retention_days,
  EXTRACT(HOURS FROM time_span) as retention_hours,

  -- Document characteristics
  ROUND(avg_message_length::NUMERIC, 0) as avg_content_size,

  -- Health indicators
  CASE 
    WHEN oldest_document > CURRENT_TIMESTAMP - INTERVAL '24 hours' THEN 'HIGH_TURNOVER'
    WHEN oldest_document > CURRENT_TIMESTAMP - INTERVAL '7 days' THEN 'NORMAL_TURNOVER'  
    ELSE 'LOW_TURNOVER'
  END as turnover_rate,

  -- Efficiency assessment
  CASE 
    WHEN current_documents < 1000 THEN 'UNDERUTILIZED'
    WHEN EXTRACT(HOURS FROM time_span) < 1 THEN 'VERY_HIGH_VOLUME'
    WHEN EXTRACT(HOURS FROM time_span) < 12 THEN 'HIGH_VOLUME'
    ELSE 'NORMAL_VOLUME'
  END as volume_assessment

FROM collection_health
ORDER BY current_documents DESC;

-- QueryLeaf provides comprehensive capped collection capabilities:
-- 1. SQL-familiar syntax for MongoDB capped collection creation and management
-- 2. High-performance batch insertion with optimized write concerns
-- 3. Real-time streaming queries with tailable cursor support
-- 4. Advanced aggregation and analytics on circular buffer data
-- 5. Automated monitoring and health assessment of capped collections
-- 6. Streaming materialized views for real-time log analysis
-- 7. Natural insertion order querying without additional indexing overhead
-- 8. Integrated alerting and threshold monitoring for operational intelligence
-- 9. Multi-tenant and enterprise-scale capped collection management
-- 10. Built-in space management with circular buffer efficiency patterns

Best Practices for Capped Collection Implementation

High-Performance Logging Design

Essential principles for effective capped collection deployment:

  1. Size Planning: Calculate appropriate collection sizes based on expected throughput and retention requirements
  2. Write Optimization: Use unacknowledged writes (w:0) for maximum throughput in logging scenarios
  3. Query Patterns: Leverage natural insertion order for efficient time-based queries
  4. Streaming Integration: Implement tailable cursors for real-time log processing and analysis
  5. Monitoring Strategy: Track collection utilization and performance metrics continuously
  6. Retention Management: Design retention policies that align with business and compliance requirements

Production Deployment Strategies

Optimize capped collection deployments for enterprise environments:

  1. Capacity Planning: Model storage requirements based on peak logging volumes and retention needs
  2. Performance Tuning: Configure appropriate write concerns and batch sizes for optimal throughput
  3. Monitoring Integration: Implement comprehensive monitoring for collection health and performance
  4. Backup Strategy: Design backup approaches that account for continuous data rotation
  5. Multi-tenant Architecture: Implement tenant isolation strategies for shared logging infrastructure
  6. Disaster Recovery: Plan for collection recreation and historical data restoration procedures

Conclusion

MongoDB capped collections provide an elegant and efficient solution for high-throughput logging, event streaming, and fixed-size data management scenarios where traditional database approaches struggle with performance and storage management complexity. The built-in circular buffer functionality, combined with optimized write performance and real-time streaming capabilities, makes capped collections ideal for modern applications requiring high-volume data ingestion with predictable storage characteristics.

Key MongoDB Capped Collections benefits include:

  • Fixed-Size Storage: Automatic space management with predictable storage utilization
  • High-Throughput Writes: Optimized for append-only workloads with minimal performance overhead
  • Natural Ordering: Preservation of insertion order without additional indexing requirements
  • Real-time Streaming: Native tailable cursor support for live data processing
  • Circular Buffer Efficiency: Automatic old document removal without manual maintenance processes
  • SQL Compatibility: Familiar SQL-style operations through QueryLeaf integration for accessible management

Whether you're building high-performance logging systems, real-time event processing platforms, system monitoring solutions, or any application requiring efficient circular buffer functionality, MongoDB capped collections with QueryLeaf's familiar SQL interface provide the foundation for scalable, maintainable data management.

QueryLeaf Integration: QueryLeaf automatically manages MongoDB capped collection operations while providing SQL-familiar syntax for collection creation, high-volume data insertion, real-time streaming, and monitoring. Advanced capped collection patterns, tailable cursors, and circular buffer management are seamlessly accessible through familiar SQL constructs, making high-performance logging both powerful and approachable for SQL-oriented development teams.

The combination of MongoDB's robust capped collection capabilities with SQL-style operations makes it an ideal platform for applications requiring high-throughput data ingestion and efficient storage management, ensuring your logging and event streaming solutions can scale effectively while maintaining predictable performance characteristics as data volumes grow.

MongoDB GridFS and Binary Data Management: Advanced File Storage Patterns for Scalable Document-Based Applications

Modern applications increasingly require sophisticated file storage capabilities that can handle diverse binary data types, massive file sizes, and complex metadata requirements while providing seamless integration with application data models. Traditional file storage approaches often create architectural complexity, separate storage silos, and synchronization challenges that become problematic as applications scale and evolve.

MongoDB GridFS provides a comprehensive solution for storing and managing large files within MongoDB itself, enabling seamless integration between file storage and document data while supporting advanced features like streaming, chunking, versioning, and metadata management. Unlike external file storage systems that require complex coordination mechanisms, GridFS offers native MongoDB integration with automatic sharding, replication, and backup capabilities that ensure file storage scales with application requirements.

The Traditional File Storage Challenge

Conventional file storage approaches often struggle with scalability, consistency, and integration complexity:

-- Traditional PostgreSQL file storage with external file system coordination challenges

-- File metadata table with limited integration capabilities  
CREATE TABLE file_metadata (
  file_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  filename VARCHAR(255) NOT NULL,
  original_filename VARCHAR(255) NOT NULL,
  file_path TEXT NOT NULL,
  file_size BIGINT NOT NULL,
  content_type VARCHAR(100),
  upload_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  uploaded_by UUID REFERENCES users(user_id),
  file_hash VARCHAR(64),

  -- Basic metadata fields
  storage_location VARCHAR(50) DEFAULT 'local',
  is_public BOOLEAN DEFAULT FALSE,
  access_level VARCHAR(20) DEFAULT 'private',

  -- Versioning attempt (complex to manage)
  version_number INTEGER DEFAULT 1,
  parent_file_id UUID REFERENCES file_metadata(file_id),

  -- Status tracking
  processing_status VARCHAR(20) DEFAULT 'uploaded',
  last_accessed TIMESTAMP
);

-- Separate table for file associations (loose coupling problems)
CREATE TABLE document_files (
  document_id UUID NOT NULL,
  file_id UUID NOT NULL,
  relationship_type VARCHAR(50) NOT NULL, -- attachment, image, document, etc.
  display_order INTEGER,
  is_primary BOOLEAN DEFAULT FALSE,
  added_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (document_id, file_id)
);

-- Complex query requiring multiple joins and external file system coordination
SELECT 
  d.document_id,
  d.title,
  d.content,
  d.created_at,

  -- File information requires complex aggregation
  json_agg(
    json_build_object(
      'file_id', fm.file_id,
      'filename', fm.filename,
      'original_filename', fm.original_filename,
      'file_size', fm.file_size,
      'content_type', fm.content_type,
      'file_path', fm.file_path, -- External file system path
      'relationship_type', df.relationship_type,
      'display_order', df.display_order,
      'is_primary', df.is_primary,
      'file_exists', (
        -- Expensive file system check required for each file
        CASE WHEN pg_stat_file(fm.file_path) IS NOT NULL 
             THEN TRUE ELSE FALSE END
      ),
      'accessible', (
        -- Additional access control complexity
        CASE WHEN fm.access_level = 'public' OR fm.uploaded_by = $2
             THEN TRUE ELSE FALSE END
      )
    ) ORDER BY df.display_order
  ) FILTER (WHERE fm.file_id IS NOT NULL) as files,

  -- File statistics aggregation
  COUNT(fm.file_id) as file_count,
  SUM(fm.file_size) as total_file_size,
  MAX(fm.upload_timestamp) as latest_file_upload

FROM documents d
LEFT JOIN document_files df ON d.document_id = df.document_id
LEFT JOIN file_metadata fm ON df.file_id = fm.file_id 
  AND fm.processing_status = 'completed'
WHERE d.user_id = $1 
  AND d.status = 'active'
  AND (fm.access_level = 'public' OR fm.uploaded_by = $1 OR $1 IN (
    SELECT user_id FROM document_permissions 
    WHERE document_id = d.document_id AND permission_level IN ('read', 'write', 'admin')
  ))
GROUP BY d.document_id, d.title, d.content, d.created_at
ORDER BY d.created_at DESC
LIMIT 50;

-- Problems with traditional file storage approaches:
-- 1. File system and database synchronization complexity
-- 2. Backup and replication coordination between file system and database
-- 3. Transactional integrity challenges across file system and database operations
-- 4. Complex access control implementation across multiple storage layers
-- 5. Difficulty implementing file versioning and history tracking
-- 6. Storage location management and migration complexity
-- 7. Limited file metadata search and indexing capabilities
-- 8. Performance bottlenecks with large numbers of files
-- 9. Scalability challenges with distributed file storage
-- 10. Complex error handling and recovery across multiple storage systems

-- File upload handling complexity (application layer)
/*
const multer = require('multer');
const path = require('path');
const fs = require('fs').promises;
const crypto = require('crypto');

class TraditionalFileStorage {
  constructor(storageConfig) {
    this.storagePath = storageConfig.storagePath;
    this.maxFileSize = storageConfig.maxFileSize || 10 * 1024 * 1024; // 10MB
    this.allowedTypes = storageConfig.allowedTypes || [];

    // Complex storage configuration
    this.storage = multer.diskStorage({
      destination: async (req, file, cb) => {
        const userDir = path.join(this.storagePath, req.user.id.toString());

        try {
          await fs.mkdir(userDir, { recursive: true });
          cb(null, userDir);
        } catch (error) {
          cb(error);
        }
      },

      filename: (req, file, cb) => {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        const fileExtension = path.extname(file.originalname);
        cb(null, file.fieldname + '-' + uniqueSuffix + fileExtension);
      }
    });
  }

  async handleFileUpload(req, res, next) {
    const upload = multer({
      storage: this.storage,
      limits: { fileSize: this.maxFileSize },
      fileFilter: (req, file, cb) => {
        if (this.allowedTypes.length > 0 && 
            !this.allowedTypes.includes(file.mimetype)) {
          cb(new Error('File type not allowed'));
          return;
        }
        cb(null, true);
      }
    }).array('files', 10);

    upload(req, res, async (err) => {
      if (err) {
        console.error('File upload error:', err);
        return res.status(400).json({ error: err.message });
      }

      try {
        // Complex file processing and database coordination
        const filePromises = req.files.map(async (file) => {
          // Calculate file hash
          const fileBuffer = await fs.readFile(file.path);
          const fileHash = crypto.createHash('sha256')
            .update(fileBuffer).digest('hex');

          // Database transaction complexity
          const client = await pool.connect();
          try {
            await client.query('BEGIN');

            // Insert file metadata
            const fileResult = await client.query(`
              INSERT INTO file_metadata (
                filename, original_filename, file_path, file_size, 
                content_type, uploaded_by, file_hash
              ) VALUES ($1, $2, $3, $4, $5, $6, $7)
              RETURNING file_id
            `, [
              file.filename,
              file.originalname,
              file.path,
              file.size,
              file.mimetype,
              req.user.id,
              fileHash
            ]);

            // Associate with document if specified
            if (req.body.document_id) {
              await client.query(`
                INSERT INTO document_files (
                  document_id, file_id, relationship_type, display_order
                ) VALUES ($1, $2, $3, $4)
              `, [
                req.body.document_id,
                fileResult.rows[0].file_id,
                req.body.relationship_type || 'attachment',
                parseInt(req.body.display_order) || 0
              ]);
            }

            await client.query('COMMIT');
            return {
              file_id: fileResult.rows[0].file_id,
              filename: file.filename,
              original_filename: file.originalname,
              file_size: file.size,
              content_type: file.mimetype
            };

          } catch (dbError) {
            await client.query('ROLLBACK');

            // Cleanup file on database error
            try {
              await fs.unlink(file.path);
            } catch (cleanupError) {
              console.error('File cleanup error:', cleanupError);
            }

            throw dbError;
          } finally {
            client.release();
          }
        });

        const uploadedFiles = await Promise.all(filePromises);
        res.json({ 
          success: true, 
          files: uploadedFiles,
          message: `${uploadedFiles.length} files uploaded successfully`
        });

      } catch (error) {
        console.error('File processing error:', error);
        res.status(500).json({ 
          error: 'File processing failed',
          details: error.message 
        });
      }
    });
  }

  async downloadFile(req, res) {
    try {
      const { file_id } = req.params;

      // Complex authorization and file access logic
      const fileQuery = `
        SELECT fm.*, dp.permission_level
        FROM file_metadata fm
        LEFT JOIN document_files df ON fm.file_id = df.file_id
        LEFT JOIN document_permissions dp ON df.document_id = dp.document_id 
          AND dp.user_id = $2
        WHERE fm.file_id = $1 
          AND (
            fm.is_public = true 
            OR fm.uploaded_by = $2 
            OR dp.permission_level IN ('read', 'write', 'admin')
          )
      `;

      const result = await pool.query(fileQuery, [file_id, req.user.id]);

      if (result.rows.length === 0) {
        return res.status(404).json({ error: 'File not found or access denied' });
      }

      const fileMetadata = result.rows[0];

      // Check if file exists on file system
      try {
        await fs.access(fileMetadata.file_path);
      } catch (error) {
        console.error('File missing from file system:', error);
        return res.status(404).json({ 
          error: 'File not found on storage system' 
        });
      }

      // Update access tracking
      await pool.query(
        'UPDATE file_metadata SET last_accessed = CURRENT_TIMESTAMP WHERE file_id = $1',
        [file_id]
      );

      // Set response headers
      res.setHeader('Content-Type', fileMetadata.content_type);
      res.setHeader('Content-Length', fileMetadata.file_size);
      res.setHeader('Content-Disposition', 
        `inline; filename="${fileMetadata.original_filename}"`);

      // Stream file
      const fileStream = require('fs').createReadStream(fileMetadata.file_path);
      fileStream.pipe(res);

      fileStream.on('error', (error) => {
        console.error('File streaming error:', error);
        if (!res.headersSent) {
          res.status(500).json({ error: 'File streaming failed' });
        }
      });

    } catch (error) {
      console.error('File download error:', error);
      res.status(500).json({ 
        error: 'File download failed',
        details: error.message 
      });
    }
  }
}

// Issues with traditional approach:
// 1. Complex file system and database coordination
// 2. Manual transaction management across storage layers
// 3. File cleanup complexity on errors
// 4. Limited streaming and chunking capabilities
// 5. Difficult backup and replication coordination
// 6. Complex access control across multiple systems
// 7. Manual file existence validation required
// 8. Limited metadata search capabilities
// 9. Scalability bottlenecks with large file counts
// 10. Error-prone manual file path management
*/

MongoDB GridFS provides comprehensive file storage with seamless integration:

// MongoDB GridFS - comprehensive file storage with advanced patterns and seamless MongoDB integration
const { MongoClient, GridFSBucket } = require('mongodb');
const { Readable } = require('stream');
const crypto = require('crypto');
const mime = require('mime-types');

const client = new MongoClient('mongodb://localhost:27017');
const db = client.db('advanced_file_management_platform');

// Advanced MongoDB GridFS file storage and management system
class AdvancedGridFSManager {
  constructor(db, options = {}) {
    this.db = db;
    this.collections = {
      documents: db.collection('documents'),
      users: db.collection('users'),
      fileAccess: db.collection('file_access_logs'),
      fileVersions: db.collection('file_versions'),
      fileSharing: db.collection('file_sharing')
    };

    // GridFS configuration for different file types and use cases
    this.gridFSBuckets = {
      // General file storage
      files: new GridFSBucket(db, { 
        bucketName: 'files',
        chunkSizeBytes: 255 * 1024 // 255KB chunks for optimal performance
      }),

      // Image storage with different chunk size for better streaming
      images: new GridFSBucket(db, {
        bucketName: 'images', 
        chunkSizeBytes: 512 * 1024 // 512KB chunks for large images
      }),

      // Video storage optimized for streaming
      videos: new GridFSBucket(db, {
        bucketName: 'videos',
        chunkSizeBytes: 1024 * 1024 // 1MB chunks for video streaming
      }),

      // Document storage for PDFs, Office files, etc.
      documents: new GridFSBucket(db, {
        bucketName: 'documents',
        chunkSizeBytes: 128 * 1024 // 128KB chunks for document files
      }),

      // Archive storage for compressed files
      archives: new GridFSBucket(db, {
        bucketName: 'archives',
        chunkSizeBytes: 2048 * 1024 // 2MB chunks for large archives
      })
    };

    // Advanced file management configuration
    this.config = {
      maxFileSize: options.maxFileSize || 100 * 1024 * 1024, // 100MB default
      allowedMimeTypes: options.allowedMimeTypes || [],
      enableVersioning: options.enableVersioning !== false,
      enableThumbnails: options.enableThumbnails !== false,
      enableVirusScanning: options.enableVirusScanning || false,
      compressionEnabled: options.compressionEnabled || false,
      encryptionEnabled: options.encryptionEnabled || false,
      accessLogging: options.accessLogging !== false,
      automaticCleanup: options.automaticCleanup !== false
    };

    // File processing pipelines
    this.processors = new Map();
    this.thumbnailGenerators = new Map();
    this.metadataExtractors = new Map();

    this.setupFileProcessors();
    this.setupMetadataExtractors();
    this.setupThumbnailGenerators();
  }

  async uploadFile(fileStream, metadata, options = {}) {
    console.log(`Uploading file: ${metadata.filename}`);

    try {
      // Validate file and metadata
      const validationResult = await this.validateFileUpload(fileStream, metadata, options);
      if (!validationResult.valid) {
        throw new Error(`File validation failed: ${validationResult.errors.join(', ')}`);
      }

      // Determine appropriate GridFS bucket based on file type
      const bucketName = this.determineBucket(metadata.contentType);
      const gridFSBucket = this.gridFSBuckets[bucketName];

      // Enhanced metadata with comprehensive file information
      const enhancedMetadata = {
        // Original metadata
        filename: metadata.filename,
        contentType: metadata.contentType || mime.lookup(metadata.filename) || 'application/octet-stream',

        // File characteristics
        originalSize: metadata.size,
        uploadedAt: new Date(),
        uploadedBy: metadata.uploadedBy,

        // Advanced metadata
        fileHash: null, // Will be calculated during upload
        bucketName: bucketName,
        chunkSize: gridFSBucket.s.options.chunkSizeBytes,

        // Application context
        documentId: metadata.documentId,
        projectId: metadata.projectId,
        organizationId: metadata.organizationId,

        // Access control and permissions
        accessLevel: metadata.accessLevel || 'private',
        permissions: metadata.permissions || {},
        isPublic: metadata.isPublic || false,

        // File relationships and organization
        category: metadata.category || 'general',
        tags: metadata.tags || [],
        description: metadata.description,

        // Versioning information
        version: options.version || 1,
        parentFileId: metadata.parentFileId,
        versionHistory: [],

        // Processing status
        processingStatus: 'uploading',
        processingSteps: [],

        // Performance and optimization
        compressionApplied: false,
        encryptionApplied: false,
        thumbnailGenerated: false,
        metadataExtracted: false,

        // Usage tracking
        downloadCount: 0,
        lastAccessed: null,
        lastModified: new Date(),

        // Storage optimization
        storageOptimized: false,
        deduplicationChecked: false,
        duplicateOf: null,

        // Custom metadata fields
        customMetadata: metadata.customMetadata || {}
      };

      // Create upload stream with comprehensive error handling
      const uploadStream = gridFSBucket.openUploadStream(metadata.filename, {
        metadata: enhancedMetadata,

        // Advanced GridFS options
        chunkSizeBytes: gridFSBucket.s.options.chunkSizeBytes,
        disableMD5: false, // Enable MD5 for file integrity
      });

      // File processing pipeline setup
      let fileHash = crypto.createHash('sha256');
      let totalBytes = 0;
      let compressionStream = null;
      let encryptionStream = null;

      // Setup processing streams if enabled
      if (this.config.compressionEnabled && this.shouldCompress(metadata.contentType)) {
        compressionStream = this.createCompressionStream();
      }

      if (this.config.encryptionEnabled && metadata.encrypted) {
        encryptionStream = this.createEncryptionStream(metadata.encryptionKey);
      }

      // Promise-based upload handling with comprehensive progress tracking
      return new Promise((resolve, reject) => {
        let processingChain = fileStream;

        // Build processing chain
        if (compressionStream) {
          processingChain = processingChain.pipe(compressionStream);
        }

        if (encryptionStream) {
          processingChain = processingChain.pipe(encryptionStream);
        }

        // File data processing during upload
        processingChain.on('data', (chunk) => {
          fileHash.update(chunk);
          totalBytes += chunk.length;

          // Emit progress events
          this.emit('uploadProgress', {
            filename: metadata.filename,
            bytesUploaded: totalBytes,
            totalBytes: metadata.size,
            progress: metadata.size ? (totalBytes / metadata.size) * 100 : 0
          });
        });

        // Stream to GridFS
        processingChain.pipe(uploadStream);

        uploadStream.on('error', async (error) => {
          console.error(`GridFS upload error for ${metadata.filename}:`, error);

          // Cleanup partial upload
          try {
            await this.cleanupFailedUpload(uploadStream.id, bucketName);
          } catch (cleanupError) {
            console.error('Upload cleanup error:', cleanupError);
          }

          reject(error);
        });

        uploadStream.on('finish', async () => {
          try {
            console.log(`File upload completed: ${metadata.filename} (${uploadStream.id})`);

            // Update file metadata with calculated information
            const calculatedHash = fileHash.digest('hex');

            const updateResult = await this.collections.files.updateOne(
              { _id: uploadStream.id },
              {
                $set: {
                  'metadata.fileHash': calculatedHash,
                  'metadata.actualSize': totalBytes,
                  'metadata.compressionApplied': compressionStream !== null,
                  'metadata.encryptionApplied': encryptionStream !== null,
                  'metadata.processingStatus': 'uploaded',
                  'metadata.uploadCompletedAt': new Date()
                }
              }
            );

            // Check for duplicate files based on hash
            const duplicateCheck = await this.checkForDuplicates(calculatedHash, uploadStream.id);

            // Post-upload processing
            const postProcessingTasks = [
              this.extractFileMetadata(uploadStream.id, bucketName, metadata.contentType),
              this.generateThumbnails(uploadStream.id, bucketName, metadata.contentType),
              this.performVirusScanning(uploadStream.id, bucketName),
              this.logFileAccess(uploadStream.id, 'upload', metadata.uploadedBy),
              this.updateFileVersionHistory(uploadStream.id, metadata.parentFileId),
              this.triggerFileWebhooks(uploadStream.id, 'file.uploaded')
            ];

            // Execute post-processing tasks
            const processingResults = await Promise.allSettled(postProcessingTasks);

            // Track processing failures
            const failedProcessing = processingResults
              .filter(result => result.status === 'rejected')
              .map(result => result.reason);

            if (failedProcessing.length > 0) {
              console.warn(`Post-processing warnings for ${metadata.filename}:`, failedProcessing);
            }

            // Final file information
            const fileInfo = {
              fileId: uploadStream.id,
              filename: metadata.filename,
              contentType: metadata.contentType,
              size: totalBytes,
              uploadedAt: new Date(),
              fileHash: calculatedHash,
              bucketName: bucketName,
              gridFSId: uploadStream.id,

              // Processing results
              processingStatus: failedProcessing.length === 0 ? 'completed' : 'completed_with_warnings',
              processingWarnings: failedProcessing,

              // Duplication information
              duplicateInfo: duplicateCheck,

              // URLs for file access
              downloadUrl: this.generateDownloadUrl(uploadStream.id, bucketName),
              streamUrl: this.generateStreamUrl(uploadStream.id, bucketName),
              thumbnailUrl: metadata.contentType.startsWith('image/') ? 
                this.generateThumbnailUrl(uploadStream.id) : null,

              // Metadata
              metadata: enhancedMetadata
            };

            // Update processing status
            await this.collections.files.updateOne(
              { _id: uploadStream.id },
              {
                $set: {
                  'metadata.processingStatus': fileInfo.processingStatus,
                  'metadata.processingCompletedAt': new Date(),
                  'metadata.processingWarnings': failedProcessing
                }
              }
            );

            resolve(fileInfo);

          } catch (error) {
            console.error(`Post-upload processing error for ${metadata.filename}:`, error);
            reject(error);
          }
        });
      });

    } catch (error) {
      console.error(`File upload error for ${metadata.filename}:`, error);
      throw error;
    }
  }

  async downloadFile(fileId, options = {}) {
    console.log(`Downloading file: ${fileId}`);

    try {
      // Get file information
      const fileInfo = await this.getFileInfo(fileId);
      if (!fileInfo) {
        throw new Error(`File not found: ${fileId}`);
      }

      // Authorization check
      if (options.userId) {
        const authorized = await this.checkFileAccess(fileId, options.userId, 'read');
        if (!authorized) {
          throw new Error('Access denied');
        }
      }

      // Determine appropriate bucket
      const bucketName = fileInfo.metadata?.bucketName || 'files';
      const gridFSBucket = this.gridFSBuckets[bucketName];

      // Create download stream
      const downloadStream = gridFSBucket.openDownloadStream(fileId);

      // Setup stream processing if needed
      let processingChain = downloadStream;

      if (fileInfo.metadata?.encryptionApplied && options.decryptionKey) {
        const decryptionStream = this.createDecryptionStream(options.decryptionKey);
        processingChain = processingChain.pipe(decryptionStream);
      }

      if (fileInfo.metadata?.compressionApplied) {
        const decompressionStream = this.createDecompressionStream();
        processingChain = processingChain.pipe(decompressionStream);
      }

      // Log file access
      if (options.userId) {
        await this.logFileAccess(fileId, 'download', options.userId);

        // Update access statistics
        await this.collections.files.updateOne(
          { _id: fileId },
          {
            $inc: { 'metadata.downloadCount': 1 },
            $set: { 'metadata.lastAccessed': new Date() }
          }
        );
      }

      // Return stream with file information
      return {
        stream: processingChain,
        fileInfo: fileInfo,
        contentType: fileInfo.contentType,
        contentLength: fileInfo.length,
        filename: fileInfo.filename,

        // Additional headers for HTTP response
        headers: {
          'Content-Type': fileInfo.contentType,
          'Content-Length': fileInfo.length,
          'Content-Disposition': `${options.disposition || 'inline'}; filename="${fileInfo.filename}"`,
          'Cache-Control': options.cacheControl || 'private, max-age=3600',
          'ETag': fileInfo.metadata?.fileHash,
          'Last-Modified': fileInfo.uploadDate.toUTCString()
        }
      };

    } catch (error) {
      console.error(`File download error for ${fileId}:`, error);
      throw error;
    }
  }

  async searchFiles(query, options = {}) {
    console.log(`Searching files with query:`, query);

    try {
      // Build comprehensive search pipeline
      const searchPipeline = [
        // Stage 1: Initial filtering based on search criteria
        {
          $match: {
            ...this.buildFileSearchFilter(query, options),
            // Ensure we're searching in the files collection
            filename: { $exists: true }
          }
        },

        // Stage 2: Add computed fields for search relevance
        {
          $addFields: {
            // Text search relevance scoring
            textScore: {
              $cond: {
                if: { $ne: [query.text, null] },
                then: {
                  $add: [
                    // Filename match weight
                    { $cond: { 
                      if: { $regexMatch: { input: '$filename', regex: query.text, options: 'i' } },
                      then: 10, else: 0 
                    }},
                    // Description match weight
                    { $cond: { 
                      if: { $regexMatch: { input: '$metadata.description', regex: query.text, options: 'i' } },
                      then: 5, else: 0 
                    }},
                    // Tags match weight
                    { $cond: { 
                      if: { $in: [query.text, '$metadata.tags'] },
                      then: 8, else: 0 
                    }},
                    // Category match weight
                    { $cond: { 
                      if: { $regexMatch: { input: '$metadata.category', regex: query.text, options: 'i' } },
                      then: 3, else: 0 
                    }}
                  ]
                },
                else: 0
              }
            },

            // Recency scoring (newer files get higher scores)
            recencyScore: {
              $divide: [
                { $subtract: [new Date(), '$uploadDate'] },
                86400000 // Convert to days
              ]
            },

            // Popularity scoring based on download count
            popularityScore: {
              $multiply: [
                { $log10: { $add: ['$metadata.downloadCount', 1] } },
                2
              ]
            },

            // Size category for filtering
            sizeCategory: {
              $switch: {
                branches: [
                  { case: { $lt: ['$length', 1024 * 1024] }, then: 'small' }, // < 1MB
                  { case: { $lt: ['$length', 10 * 1024 * 1024] }, then: 'medium' }, // < 10MB
                  { case: { $lt: ['$length', 100 * 1024 * 1024] }, then: 'large' }, // < 100MB
                ],
                default: 'very_large'
              }
            }
          }
        },

        // Stage 3: Apply advanced filtering
        {
          $match: {
            ...(query.sizeCategory && { sizeCategory: query.sizeCategory }),
            ...(query.minScore && { textScore: { $gte: query.minScore } })
          }
        },

        // Stage 4: Lookup related document information if file is associated
        {
          $lookup: {
            from: 'documents',
            localField: 'metadata.documentId',
            foreignField: '_id',
            as: 'documentInfo',
            pipeline: [
              {
                $project: {
                  title: 1,
                  status: 1,
                  createdBy: 1,
                  projectId: 1
                }
              }
            ]
          }
        },

        // Stage 5: Lookup user information for uploaded_by
        {
          $lookup: {
            from: 'users',
            localField: 'metadata.uploadedBy',
            foreignField: '_id',
            as: 'uploaderInfo',
            pipeline: [
              {
                $project: {
                  name: 1,
                  email: 1,
                  avatar: 1
                }
              }
            ]
          }
        },

        // Stage 6: Calculate final relevance score
        {
          $addFields: {
            relevanceScore: {
              $add: [
                '$textScore',
                { $divide: ['$popularityScore', 4] },
                { $cond: { if: { $lt: ['$recencyScore', 30] }, then: 5, else: 0 } }, // Bonus for files < 30 days old
                { $cond: { if: { $gt: [{ $size: '$documentInfo' }, 0] }, then: 2, else: 0 } } // Bonus for associated files
              ]
            }
          }
        },

        // Stage 7: Project final result structure
        {
          $project: {
            fileId: '$_id',
            filename: 1,
            contentType: 1,
            length: 1,
            uploadDate: 1,

            // Metadata information
            category: '$metadata.category',
            tags: '$metadata.tags',
            description: '$metadata.description',
            accessLevel: '$metadata.accessLevel',
            isPublic: '$metadata.isPublic',

            // File characteristics
            fileHash: '$metadata.fileHash',
            bucketName: '$metadata.bucketName',
            downloadCount: '$metadata.downloadCount',
            lastAccessed: '$metadata.lastAccessed',

            // Processing status
            processingStatus: '$metadata.processingStatus',
            thumbnailGenerated: '$metadata.thumbnailGenerated',

            // Computed scores
            textScore: 1,
            popularityScore: 1,
            relevanceScore: 1,
            sizeCategory: 1,

            // Related information
            documentInfo: { $arrayElemAt: ['$documentInfo', 0] },
            uploaderInfo: { $arrayElemAt: ['$uploaderInfo', 0] },

            // Access URLs
            downloadUrl: {
              $concat: [
                '/api/files/',
                { $toString: '$_id' },
                '/download'
              ]
            },

            thumbnailUrl: {
              $cond: {
                if: { $eq: ['$metadata.thumbnailGenerated', true] },
                then: {
                  $concat: [
                    '/api/files/',
                    { $toString: '$_id' },
                    '/thumbnail'
                  ]
                },
                else: null
              }
            },

            // Formatted file information
            formattedSize: {
              $switch: {
                branches: [
                  { 
                    case: { $lt: ['$length', 1024] },
                    then: { $concat: [{ $toString: '$length' }, ' bytes'] }
                  },
                  { 
                    case: { $lt: ['$length', 1024 * 1024] },
                    then: { 
                      $concat: [
                        { $toString: { $round: [{ $divide: ['$length', 1024] }, 1] } },
                        ' KB'
                      ]
                    }
                  },
                  { 
                    case: { $lt: ['$length', 1024 * 1024 * 1024] },
                    then: { 
                      $concat: [
                        { $toString: { $round: [{ $divide: ['$length', 1024 * 1024] }, 1] } },
                        ' MB'
                      ]
                    }
                  }
                ],
                default: { 
                  $concat: [
                    { $toString: { $round: [{ $divide: ['$length', 1024 * 1024 * 1024] }, 1] } },
                    ' GB'
                  ]
                }
              }
            }
          }
        },

        // Stage 8: Sort by relevance and apply pagination
        { $sort: this.buildSearchSort(options.sortBy, options.sortOrder) },
        { $skip: options.skip || 0 },
        { $limit: options.limit || 20 }
      ];

      // Execute search pipeline
      const searchResults = await this.db.collection('fs.files').aggregate(searchPipeline).toArray();

      // Get total count for pagination
      const totalCountPipeline = [
        { $match: this.buildFileSearchFilter(query, options) },
        { $count: 'total' }
      ];

      const countResult = await this.db.collection('fs.files').aggregate(totalCountPipeline).toArray();
      const totalCount = countResult.length > 0 ? countResult[0].total : 0;

      return {
        files: searchResults,
        pagination: {
          total: totalCount,
          page: Math.floor((options.skip || 0) / (options.limit || 20)) + 1,
          limit: options.limit || 20,
          pages: Math.ceil(totalCount / (options.limit || 20))
        },
        query: query,
        searchTime: Date.now() - (options.startTime || Date.now()),

        // Search analytics
        analytics: {
          averageRelevanceScore: searchResults.length > 0 ? 
            searchResults.reduce((sum, file) => sum + file.relevanceScore, 0) / searchResults.length : 0,
          categoryDistribution: this.analyzeCategoryDistribution(searchResults),
          sizeDistribution: this.analyzeSizeDistribution(searchResults),
          contentTypeDistribution: this.analyzeContentTypeDistribution(searchResults)
        }
      };

    } catch (error) {
      console.error('File search error:', error);
      throw error;
    }
  }

  async manageFileVersions(fileId, operation, options = {}) {
    console.log(`Managing file versions for ${fileId}, operation: ${operation}`);

    try {
      switch (operation) {
        case 'create_version':
          return await this.createFileVersion(fileId, options);

        case 'list_versions':
          return await this.listFileVersions(fileId, options);

        case 'restore_version':
          return await this.restoreFileVersion(fileId, options.versionId);

        case 'delete_version':
          return await this.deleteFileVersion(fileId, options.versionId);

        case 'compare_versions':
          return await this.compareFileVersions(fileId, options.versionId1, options.versionId2);

        default:
          throw new Error(`Unknown version operation: ${operation}`);
      }
    } catch (error) {
      console.error(`File version management error for ${fileId}:`, error);
      throw error;
    }
  }

  async createFileVersion(originalFileId, options) {
    console.log(`Creating new version for file: ${originalFileId}`);

    const session = this.db.client.startSession();

    try {
      await session.withTransaction(async () => {
        // Get original file information
        const originalFile = await this.getFileInfo(originalFileId);
        if (!originalFile) {
          throw new Error(`Original file not found: ${originalFileId}`);
        }

        // Create new version metadata
        const versionMetadata = {
          ...originalFile.metadata,
          version: (originalFile.metadata?.version || 1) + 1,
          parentFileId: originalFileId,
          versionCreatedAt: new Date(),
          versionCreatedBy: options.userId,
          versionNotes: options.versionNotes,
          isCurrentVersion: true
        };

        // Upload new version
        const newVersionInfo = await this.uploadFile(options.fileStream, versionMetadata, {
          version: versionMetadata.version
        });

        // Update original file to mark as not current
        await this.collections.files.updateOne(
          { _id: originalFileId },
          {
            $set: { 'metadata.isCurrentVersion': false },
            $push: {
              'metadata.versionHistory': {
                versionId: newVersionInfo.fileId,
                version: versionMetadata.version,
                createdAt: versionMetadata.versionCreatedAt,
                createdBy: versionMetadata.versionCreatedBy,
                notes: versionMetadata.versionNotes
              }
            }
          }
        );

        // Update version references in related documents
        if (originalFile.metadata?.documentId) {
          await this.collections.documents.updateMany(
            { 'files.fileId': originalFileId },
            {
              $set: { 'files.$.fileId': newVersionInfo.fileId },
              $push: {
                'files.$.versionHistory': {
                  previousFileId: originalFileId,
                  newFileId: newVersionInfo.fileId,
                  versionedAt: new Date(),
                  versionedBy: options.userId
                }
              }
            }
          );
        }

        return newVersionInfo;
      });

    } catch (error) {
      console.error(`File version creation error for ${originalFileId}:`, error);
      throw error;
    } finally {
      await session.endSession();
    }
  }

  // Helper methods for advanced file processing

  determineBucket(contentType) {
    if (contentType.startsWith('image/')) return 'images';
    if (contentType.startsWith('video/')) return 'videos';
    if (contentType.includes('pdf') || 
        contentType.includes('document') || 
        contentType.includes('word') || 
        contentType.includes('excel') || 
        contentType.includes('powerpoint')) return 'documents';
    if (contentType.includes('zip') || 
        contentType.includes('tar') || 
        contentType.includes('compress')) return 'archives';
    return 'files';
  }

  async validateFileUpload(fileStream, metadata, options) {
    const errors = [];

    // Size validation
    if (metadata.size > this.config.maxFileSize) {
      errors.push(`File size ${metadata.size} exceeds maximum ${this.config.maxFileSize}`);
    }

    // MIME type validation
    if (this.config.allowedMimeTypes.length > 0 && 
        !this.config.allowedMimeTypes.includes(metadata.contentType)) {
      errors.push(`Content type ${metadata.contentType} is not allowed`);
    }

    // Filename validation
    if (!metadata.filename || metadata.filename.trim().length === 0) {
      errors.push('Filename is required');
    }

    return { valid: errors.length === 0, errors };
  }

  buildFileSearchFilter(query, options) {
    const filter = {};

    // Text search across multiple fields
    if (query.text) {
      filter.$or = [
        { filename: { $regex: query.text, $options: 'i' } },
        { 'metadata.description': { $regex: query.text, $options: 'i' } },
        { 'metadata.tags': { $in: [new RegExp(query.text, 'i')] } },
        { 'metadata.category': { $regex: query.text, $options: 'i' } }
      ];
    }

    // Content type filtering
    if (query.contentType) {
      if (Array.isArray(query.contentType)) {
        filter.contentType = { $in: query.contentType };
      } else {
        filter.contentType = { $regex: query.contentType, $options: 'i' };
      }
    }

    // Date range filtering
    if (query.uploadedAfter || query.uploadedBefore) {
      filter.uploadDate = {};
      if (query.uploadedAfter) filter.uploadDate.$gte = new Date(query.uploadedAfter);
      if (query.uploadedBefore) filter.uploadDate.$lte = new Date(query.uploadedBefore);
    }

    // Size range filtering
    if (query.minSize || query.maxSize) {
      filter.length = {};
      if (query.minSize) filter.length.$gte = query.minSize;
      if (query.maxSize) filter.length.$lte = query.maxSize;
    }

    // Category filtering
    if (query.category) {
      filter['metadata.category'] = query.category;
    }

    // Tags filtering
    if (query.tags) {
      const tags = Array.isArray(query.tags) ? query.tags : [query.tags];
      filter['metadata.tags'] = { $in: tags };
    }

    // Uploader filtering
    if (query.uploadedBy) {
      filter['metadata.uploadedBy'] = query.uploadedBy;
    }

    // Access level filtering
    if (query.accessLevel) {
      filter['metadata.accessLevel'] = query.accessLevel;
    }

    // Document association filtering
    if (query.documentId) {
      filter['metadata.documentId'] = query.documentId;
    }

    // Processing status filtering
    if (query.processingStatus) {
      filter['metadata.processingStatus'] = query.processingStatus;
    }

    return filter;
  }

  buildSearchSort(sortBy = 'relevance', sortOrder = 'desc') {
    const sortDirection = sortOrder === 'desc' ? -1 : 1;

    switch (sortBy) {
      case 'relevance':
        return { relevanceScore: -1, uploadDate: -1 };
      case 'name':
        return { filename: sortDirection };
      case 'size':
        return { length: sortDirection };
      case 'date':
        return { uploadDate: sortDirection };
      case 'popularity':
        return { popularityScore: -1, uploadDate: -1 };
      case 'type':
        return { contentType: sortDirection, filename: 1 };
      default:
        return { relevanceScore: -1, uploadDate: -1 };
    }
  }

  setupFileProcessors() {
    // Image processing
    this.processors.set('image', async (fileId, contentType) => {
      // Implement image processing (resize, optimize, etc.)
      console.log(`Processing image: ${fileId}`);
    });

    // Document processing
    this.processors.set('document', async (fileId, contentType) => {
      // Implement document processing (text extraction, etc.)
      console.log(`Processing document: ${fileId}`);
    });

    // Video processing
    this.processors.set('video', async (fileId, contentType) => {
      // Implement video processing (thumbnail, compression, etc.)
      console.log(`Processing video: ${fileId}`);
    });
  }

  setupThumbnailGenerators() {
    // Image thumbnail generation
    this.thumbnailGenerators.set('image', async (fileId) => {
      console.log(`Generating image thumbnail for: ${fileId}`);
      // Implement image thumbnail generation
    });

    // PDF thumbnail generation
    this.thumbnailGenerators.set('pdf', async (fileId) => {
      console.log(`Generating PDF thumbnail for: ${fileId}`);
      // Implement PDF thumbnail generation
    });
  }

  setupMetadataExtractors() {
    // Image metadata extraction (EXIF, etc.)
    this.metadataExtractors.set('image', async (fileId) => {
      console.log(`Extracting image metadata for: ${fileId}`);
      // Implement EXIF and other metadata extraction
    });

    // Document metadata extraction
    this.metadataExtractors.set('document', async (fileId) => {
      console.log(`Extracting document metadata for: ${fileId}`);
      // Implement document properties extraction
    });
  }
}

// Benefits of MongoDB GridFS Advanced File Management:
// - Seamless integration with MongoDB data model and queries
// - Automatic file chunking and streaming for large files
// - Built-in file versioning and history tracking
// - Comprehensive metadata management and search capabilities
// - Advanced file processing pipelines and thumbnail generation
// - Integrated access control and permission management
// - Automatic backup and replication with MongoDB cluster
// - Sophisticated file search with relevance scoring
// - Real-time file access logging and analytics
// - SQL-compatible file operations through QueryLeaf integration

module.exports = {
  AdvancedGridFSManager
};

Understanding MongoDB GridFS Architecture

Advanced File Storage Patterns and Integration Strategies

Implement sophisticated GridFS patterns for production-scale applications:

// Production-ready GridFS management with advanced patterns and optimization
class ProductionGridFSManager extends AdvancedGridFSManager {
  constructor(db, productionConfig) {
    super(db);

    this.productionConfig = {
      ...productionConfig,
      replicationEnabled: true,
      shardingOptimized: true,
      compressionEnabled: true,
      encryptionEnabled: productionConfig.encryptionEnabled || false,
      cdnIntegration: productionConfig.cdnIntegration || false,
      virusScanning: productionConfig.virusScanning || false,
      contentDelivery: productionConfig.contentDelivery || false
    };

    this.setupProductionOptimizations();
    this.setupMonitoringAndAlerts();
    this.setupCDNIntegration();
  }

  async implementFileStorageStrategy(storageRequirements) {
    console.log('Implementing production file storage strategy...');

    const strategy = {
      storageDistribution: await this.designStorageDistribution(storageRequirements),
      performanceOptimization: await this.implementPerformanceOptimizations(storageRequirements),
      securityMeasures: await this.implementSecurityMeasures(storageRequirements),
      monitoringSetup: await this.setupComprehensiveMonitoring(storageRequirements),
      backupStrategy: await this.designBackupStrategy(storageRequirements)
    };

    return {
      strategy: strategy,
      implementation: await this.executeStorageStrategy(strategy),
      validation: await this.validateStorageImplementation(strategy),
      documentation: this.generateStorageDocumentation(strategy)
    };
  }

  async setupAdvancedFileCaching(cachingConfig) {
    console.log('Setting up advanced file caching system...');

    const cachingStrategy = {
      // Multi-tier caching
      tiers: [
        {
          name: 'memory',
          type: 'redis',
          capacity: '2GB',
          ttl: 3600, // 1 hour
          priority: ['images', 'thumbnails', 'frequently_accessed']
        },
        {
          name: 'disk',
          type: 'filesystem',
          capacity: '100GB',
          ttl: 86400, // 24 hours
          priority: ['documents', 'archives', 'medium_access']
        },
        {
          name: 'cdn',
          type: 'cloudfront',
          capacity: 'unlimited',
          ttl: 604800, // 7 days
          priority: ['public_files', 'static_content']
        }
      ],

      // Intelligent prefetching
      prefetchingRules: [
        {
          condition: 'user_documents',
          action: 'prefetch_related_files',
          priority: 'high'
        },
        {
          condition: 'popular_content',
          action: 'cache_preemptively',
          priority: 'medium'
        }
      ],

      // Cache invalidation strategies
      invalidationRules: [
        {
          trigger: 'file_updated',
          action: 'invalidate_all_versions',
          scope: 'global'
        },
        {
          trigger: 'permission_changed',
          action: 'invalidate_user_cache',
          scope: 'user_specific'
        }
      ]
    };

    return await this.implementCachingStrategy(cachingStrategy);
  }

  async manageFileLifecycle(lifecycleConfig) {
    console.log('Managing file lifecycle policies...');

    const lifecyclePolicies = {
      // Automatic archival policies
      archival: [
        {
          name: 'inactive_files',
          condition: { lastAccessed: { $lt: new Date(Date.now() - 90 * 24 * 60 * 60 * 1000) } },
          action: 'move_to_cold_storage',
          schedule: 'daily'
        },
        {
          name: 'large_old_files',
          condition: { 
            uploadDate: { $lt: new Date(Date.now() - 365 * 24 * 60 * 60 * 1000) },
            length: { $gt: 100 * 1024 * 1024 }
          },
          action: 'compress_and_archive',
          schedule: 'weekly'
        }
      ],

      // Cleanup policies
      cleanup: [
        {
          name: 'temp_files',
          condition: { 
            'metadata.category': 'temporary',
            uploadDate: { $lt: new Date(Date.now() - 24 * 60 * 60 * 1000) }
          },
          action: 'delete',
          schedule: 'hourly'
        },
        {
          name: 'orphaned_versions',
          condition: { 'metadata.parentFileId': { $exists: true, $nin: [] } },
          action: 'cleanup_orphaned',
          schedule: 'daily'
        }
      ],

      // Optimization policies
      optimization: [
        {
          name: 'duplicate_detection',
          condition: { 'metadata.deduplicationChecked': { $ne: true } },
          action: 'check_duplicates',
          schedule: 'continuous'
        },
        {
          name: 'compression_optimization',
          condition: { 
            contentType: { $in: ['image/png', 'image/jpeg', 'image/tiff'] },
            'metadata.compressionApplied': { $ne: true },
            length: { $gt: 1024 * 1024 }
          },
          action: 'apply_compression',
          schedule: 'daily'
        }
      ]
    };

    return await this.implementLifecyclePolicies(lifecyclePolicies);
  }
}

SQL-Style GridFS Management with QueryLeaf

QueryLeaf provides familiar SQL syntax for MongoDB GridFS operations and file management:

-- QueryLeaf advanced file storage and GridFS management with SQL-familiar syntax

-- Create file storage with GridFS configuration
CREATE FILE_STORAGE advanced_file_system 
USING GRIDFS (
  bucket_name = 'application_files',
  chunk_size = 255 * 1024, -- 255KB chunks for optimal performance

  -- Advanced GridFS configuration
  enable_md5 = true,
  enable_compression = true,
  compression_algorithm = 'zlib',
  encryption_enabled = false,

  -- Storage optimization
  auto_deduplication = true,
  thumbnail_generation = true,
  metadata_extraction = true,

  -- Performance tuning
  read_preference = 'secondaryPreferred',
  write_concern = { w: 'majority', j: true },
  max_time_ms = 30000
);

-- Upload files with comprehensive metadata management
INSERT INTO files (
  filename,
  content_type,
  file_data,
  metadata
) VALUES (
  'project_proposal.pdf',
  'application/pdf',
  LOAD_FILE('/path/to/project_proposal.pdf'),
  {
    category: 'documents',
    tags: ['project', 'proposal', 'business'],
    description: 'Q4 project proposal document',
    access_level: 'team',
    project_id: '507f1f77bcf86cd799439011',
    uploaded_by: '507f1f77bcf86cd799439012',

    -- Custom metadata fields
    document_type: 'proposal',
    confidentiality: 'internal',
    review_required: true,
    expiry_date: DATE_ADD(CURRENT_DATE, INTERVAL 1 YEAR),

    -- Processing options
    generate_thumbnail: true,
    extract_text: true,
    enable_versioning: true,
    compression_level: 'medium'
  }
),
(
  'user_avatar.jpg',
  'image/jpeg', 
  LOAD_FILE('/path/to/avatar.jpg'),
  {
    category: 'images',
    tags: ['avatar', 'profile', 'user'],
    description: 'User profile avatar image',
    access_level: 'public',
    user_id: '507f1f77bcf86cd799439013',
    uploaded_by: '507f1f77bcf86cd799439013',

    -- Image-specific metadata
    image_type: 'avatar',
    max_width: 200,
    max_height: 200,
    quality: 85,

    -- Processing options  
    generate_thumbnails: ['small', 'medium', 'large'],
    extract_exif: true,
    auto_optimize: true
  }
);

-- Advanced file search with comprehensive filtering and relevance scoring
SELECT 
  f.file_id,
  f.filename,
  f.content_type,
  f.file_size,
  f.upload_date,
  f.download_count,
  f.metadata,

  -- File access URLs
  CONCAT('/api/files/', f.file_id, '/download') as download_url,
  CONCAT('/api/files/', f.file_id, '/stream') as stream_url,

  -- Conditional thumbnail URL
  CASE 
    WHEN f.content_type LIKE 'image/%' AND f.metadata.thumbnail_generated = true THEN
      CONCAT('/api/files/', f.file_id, '/thumbnail')
    ELSE NULL
  END as thumbnail_url,

  -- File size formatting
  CASE 
    WHEN f.file_size < 1024 THEN CONCAT(f.file_size, ' bytes')
    WHEN f.file_size < 1024 * 1024 THEN CONCAT(ROUND(f.file_size / 1024.0, 1), ' KB')
    WHEN f.file_size < 1024 * 1024 * 1024 THEN CONCAT(ROUND(f.file_size / (1024.0 * 1024), 1), ' MB')
    ELSE CONCAT(ROUND(f.file_size / (1024.0 * 1024 * 1024), 1), ' GB')
  END as formatted_size,

  -- Search relevance scoring
  (
    -- Filename match weight (highest)
    CASE WHEN f.filename ILIKE '%proposal%' THEN 10 ELSE 0 END +

    -- Description match weight
    CASE WHEN f.metadata.description ILIKE '%proposal%' THEN 5 ELSE 0 END +

    -- Tags match weight  
    CASE WHEN 'proposal' = ANY(f.metadata.tags) THEN 8 ELSE 0 END +

    -- Category match weight
    CASE WHEN f.metadata.category ILIKE '%proposal%' THEN 3 ELSE 0 END +

    -- Recency bonus (files uploaded within last 30 days)
    CASE WHEN f.upload_date > CURRENT_DATE - INTERVAL '30 days' THEN 5 ELSE 0 END +

    -- Popularity bonus (files with high download count)
    LEAST(LOG(f.download_count + 1) * 2, 10) +

    -- Access level bonus (public files get slight boost)
    CASE WHEN f.metadata.access_level = 'public' THEN 2 ELSE 0 END

  ) as relevance_score,

  -- File status and health
  CASE 
    WHEN f.metadata.processing_status = 'completed' THEN 'ready'
    WHEN f.metadata.processing_status = 'processing' THEN 'processing'  
    WHEN f.metadata.processing_status = 'failed' THEN 'error'
    ELSE 'unknown'
  END as file_status,

  -- Associated document information
  d.title as document_title,
  d.project_id,

  -- Uploader information
  u.name as uploaded_by_name,
  u.email as uploaded_by_email

FROM files f
LEFT JOIN documents d ON f.metadata.document_id = d.document_id
LEFT JOIN users u ON f.metadata.uploaded_by = u.user_id

WHERE 
  -- Text search across multiple fields
  (
    f.filename ILIKE '%proposal%' 
    OR f.metadata.description ILIKE '%proposal%'
    OR 'proposal' = ANY(f.metadata.tags)
    OR f.metadata.category ILIKE '%proposal%'
  )

  -- Content type filtering
  AND f.content_type IN ('application/pdf', 'application/msword', 'text/plain')

  -- Date range filtering
  AND f.upload_date >= CURRENT_DATE - INTERVAL '1 year'

  -- Size filtering (between 1KB and 50MB)
  AND f.file_size BETWEEN 1024 AND 50 * 1024 * 1024

  -- Access level filtering (user can access)
  AND (
    f.metadata.access_level = 'public'
    OR f.metadata.uploaded_by = CURRENT_USER_ID()
    OR CURRENT_USER_ID() IN (
      SELECT user_id FROM file_permissions 
      WHERE file_id = f.file_id AND permission_level IN ('read', 'write', 'admin')
    )
  )

  -- Processing status filtering
  AND f.metadata.processing_status = 'completed'

  -- Project-based filtering (if specified)
  AND (f.metadata.project_id = '507f1f77bcf86cd799439011' OR f.metadata.project_id IS NULL)

ORDER BY 
  relevance_score DESC,
  f.download_count DESC,
  f.upload_date DESC

LIMIT 20 OFFSET 0;

-- File versioning management with comprehensive history tracking
WITH file_versions AS (
  SELECT 
    f.file_id,
    f.filename,
    f.content_type,
    f.file_size,
    f.upload_date,
    f.metadata,

    -- Version information
    f.metadata.version as version_number,
    f.metadata.parent_file_id,
    f.metadata.is_current_version,
    f.metadata.version_notes,

    -- Version relationships
    LAG(f.file_id) OVER (
      PARTITION BY COALESCE(f.metadata.parent_file_id, f.file_id)
      ORDER BY f.metadata.version
    ) as previous_version_id,

    LEAD(f.file_id) OVER (
      PARTITION BY COALESCE(f.metadata.parent_file_id, f.file_id)
      ORDER BY f.metadata.version  
    ) as next_version_id,

    -- Version statistics
    COUNT(*) OVER (
      PARTITION BY COALESCE(f.metadata.parent_file_id, f.file_id)
    ) as total_versions,

    ROW_NUMBER() OVER (
      PARTITION BY COALESCE(f.metadata.parent_file_id, f.file_id)
      ORDER BY f.metadata.version DESC
    ) as version_rank

  FROM files f
  WHERE f.metadata.version IS NOT NULL
),

version_changes AS (
  SELECT 
    fv.*,

    -- Size change analysis
    fv.file_size - LAG(fv.file_size) OVER (
      PARTITION BY COALESCE(fv.metadata.parent_file_id, fv.file_id)
      ORDER BY fv.version_number
    ) as size_change,

    -- Time between versions
    fv.upload_date - LAG(fv.upload_date) OVER (
      PARTITION BY COALESCE(fv.metadata.parent_file_id, fv.file_id)  
      ORDER BY fv.version_number
    ) as time_since_previous_version,

    -- Version change type
    CASE 
      WHEN LAG(fv.file_size) OVER (
        PARTITION BY COALESCE(fv.metadata.parent_file_id, fv.file_id)
        ORDER BY fv.version_number
      ) IS NULL THEN 'initial'
      WHEN fv.file_size > LAG(fv.file_size) OVER (
        PARTITION BY COALESCE(fv.metadata.parent_file_id, fv.file_id)
        ORDER BY fv.version_number
      ) THEN 'expansion'
      WHEN fv.file_size < LAG(fv.file_size) OVER (
        PARTITION BY COALESCE(fv.metadata.parent_file_id, fv.file_id)
        ORDER BY fv.version_number
      ) THEN 'reduction'
      ELSE 'maintenance'
    END as change_type

  FROM file_versions fv
)

SELECT 
  vc.file_id,
  vc.filename,
  vc.version_number,
  vc.upload_date,
  vc.file_size,
  vc.metadata.version_notes,
  vc.is_current_version,

  -- Version navigation
  vc.previous_version_id,
  vc.next_version_id,
  vc.total_versions,
  vc.version_rank,

  -- Change analysis
  vc.size_change,
  vc.time_since_previous_version,
  vc.change_type,

  -- Formatted information
  CASE 
    WHEN vc.size_change > 0 THEN CONCAT('+', vc.size_change, ' bytes')
    WHEN vc.size_change < 0 THEN CONCAT(vc.size_change, ' bytes')
    ELSE 'No size change'
  END as formatted_size_change,

  CASE 
    WHEN vc.time_since_previous_version IS NULL THEN 'Initial version'
    WHEN EXTRACT(DAYS FROM vc.time_since_previous_version) > 0 THEN 
      CONCAT(EXTRACT(DAYS FROM vc.time_since_previous_version), ' days ago')
    WHEN EXTRACT(HOURS FROM vc.time_since_previous_version) > 0 THEN 
      CONCAT(EXTRACT(HOURS FROM vc.time_since_previous_version), ' hours ago')
    ELSE 'Less than an hour ago'
  END as formatted_time_diff,

  -- Version actions
  CASE vc.is_current_version
    WHEN true THEN 'Current Version'
    ELSE 'Restore This Version'
  END as version_action,

  -- Download URLs for each version
  CONCAT('/api/files/', vc.file_id, '/download') as download_url,
  CONCAT('/api/files/', vc.file_id, '/compare/', vc.previous_version_id) as compare_url

FROM version_changes vc
WHERE COALESCE(vc.metadata.parent_file_id, vc.file_id) = '507f1f77bcf86cd799439015'
ORDER BY vc.version_number DESC;

-- Advanced file analytics and usage reporting
WITH file_analytics AS (
  SELECT 
    f.file_id,
    f.filename,
    f.content_type,
    f.file_size,
    f.upload_date,
    f.metadata,

    -- Usage statistics
    f.download_count,
    f.metadata.last_accessed,

    -- File age and activity metrics
    EXTRACT(DAYS FROM CURRENT_TIMESTAMP - f.upload_date) as age_days,
    EXTRACT(DAYS FROM CURRENT_TIMESTAMP - f.metadata.last_accessed) as days_since_access,

    -- Usage intensity calculation
    CASE 
      WHEN EXTRACT(DAYS FROM CURRENT_TIMESTAMP - f.upload_date) > 0 THEN
        f.download_count::float / EXTRACT(DAYS FROM CURRENT_TIMESTAMP - f.upload_date)
      ELSE f.download_count::float
    END as downloads_per_day,

    -- Storage cost calculation (simplified)
    f.file_size * 0.00000012 as monthly_storage_cost_usd, -- $0.12 per GB per month

    -- File category classification
    CASE 
      WHEN f.content_type LIKE 'image/%' THEN 'Images'
      WHEN f.content_type LIKE 'video/%' THEN 'Videos' 
      WHEN f.content_type LIKE 'audio/%' THEN 'Audio'
      WHEN f.content_type IN ('application/pdf', 'application/msword', 'text/plain') THEN 'Documents'
      WHEN f.content_type LIKE 'application/%zip%' OR f.content_type LIKE '%compress%' THEN 'Archives'
      ELSE 'Other'
    END as file_category,

    -- Size category
    CASE 
      WHEN f.file_size < 1024 * 1024 THEN 'Small (<1MB)'
      WHEN f.file_size < 10 * 1024 * 1024 THEN 'Medium (1-10MB)'
      WHEN f.file_size < 100 * 1024 * 1024 THEN 'Large (10-100MB)'
      ELSE 'Very Large (>100MB)'
    END as size_category,

    -- Activity classification
    CASE 
      WHEN f.metadata.last_accessed > CURRENT_DATE - INTERVAL '7 days' THEN 'Hot'
      WHEN f.metadata.last_accessed > CURRENT_DATE - INTERVAL '30 days' THEN 'Warm'  
      WHEN f.metadata.last_accessed > CURRENT_DATE - INTERVAL '90 days' THEN 'Cool'
      ELSE 'Cold'
    END as access_temperature

  FROM files f
  WHERE f.upload_date >= CURRENT_DATE - INTERVAL '1 year'
),

aggregated_analytics AS (
  SELECT 
    -- Overall file statistics
    COUNT(*) as total_files,
    SUM(fa.file_size) as total_storage_bytes,
    AVG(fa.file_size) as avg_file_size,
    SUM(fa.download_count) as total_downloads,
    AVG(fa.download_count) as avg_downloads_per_file,
    SUM(fa.monthly_storage_cost_usd) as total_monthly_cost_usd,

    -- Category breakdown
    COUNT(*) FILTER (WHERE fa.file_category = 'Images') as image_count,
    COUNT(*) FILTER (WHERE fa.file_category = 'Documents') as document_count,
    COUNT(*) FILTER (WHERE fa.file_category = 'Videos') as video_count,
    COUNT(*) FILTER (WHERE fa.file_category = 'Archives') as archive_count,

    -- Size distribution
    COUNT(*) FILTER (WHERE fa.size_category = 'Small (<1MB)') as small_files,
    COUNT(*) FILTER (WHERE fa.size_category = 'Medium (1-10MB)') as medium_files,
    COUNT(*) FILTER (WHERE fa.size_category = 'Large (10-100MB)') as large_files,
    COUNT(*) FILTER (WHERE fa.size_category = 'Very Large (>100MB)') as very_large_files,

    -- Activity distribution
    COUNT(*) FILTER (WHERE fa.access_temperature = 'Hot') as hot_files,
    COUNT(*) FILTER (WHERE fa.access_temperature = 'Warm') as warm_files,
    COUNT(*) FILTER (WHERE fa.access_temperature = 'Cool') as cool_files,
    COUNT(*) FILTER (WHERE fa.access_temperature = 'Cold') as cold_files,

    -- Storage optimization opportunities
    SUM(fa.file_size) FILTER (WHERE fa.access_temperature = 'Cold') as cold_storage_bytes,
    COUNT(*) FILTER (WHERE fa.download_count = 0 AND fa.age_days > 90) as unused_files,

    -- Performance metrics
    AVG(fa.downloads_per_day) as avg_downloads_per_day,
    MAX(fa.downloads_per_day) as max_downloads_per_day,

    -- Trend analysis
    COUNT(*) FILTER (WHERE fa.upload_date >= CURRENT_DATE - INTERVAL '30 days') as files_last_30_days,
    COUNT(*) FILTER (WHERE fa.upload_date >= CURRENT_DATE - INTERVAL '7 days') as files_last_7_days

  FROM file_analytics fa
)

SELECT 
  -- Storage summary
  total_files,
  ROUND((total_storage_bytes / 1024.0 / 1024 / 1024)::numeric, 2) as total_storage_gb,
  ROUND((avg_file_size / 1024.0 / 1024)::numeric, 2) as avg_file_size_mb,
  ROUND(total_monthly_cost_usd::numeric, 2) as monthly_cost_usd,

  -- Usage summary
  total_downloads,
  ROUND(avg_downloads_per_file::numeric, 1) as avg_downloads_per_file,
  ROUND(avg_downloads_per_day::numeric, 2) as avg_downloads_per_day,

  -- Category distribution (percentages)
  ROUND((image_count::float / total_files * 100)::numeric, 1) as image_percentage,
  ROUND((document_count::float / total_files * 100)::numeric, 1) as document_percentage,
  ROUND((video_count::float / total_files * 100)::numeric, 1) as video_percentage,

  -- Size distribution (percentages)
  ROUND((small_files::float / total_files * 100)::numeric, 1) as small_files_percentage,
  ROUND((medium_files::float / total_files * 100)::numeric, 1) as medium_files_percentage,
  ROUND((large_files::float / total_files * 100)::numeric, 1) as large_files_percentage,
  ROUND((very_large_files::float / total_files * 100)::numeric, 1) as very_large_files_percentage,

  -- Activity distribution
  hot_files,
  warm_files, 
  cool_files,
  cold_files,

  -- Optimization opportunities
  ROUND((cold_storage_bytes / 1024.0 / 1024 / 1024)::numeric, 2) as cold_storage_gb,
  unused_files,
  ROUND((unused_files::float / total_files * 100)::numeric, 1) as unused_files_percentage,

  -- Growth trends
  files_last_30_days,
  files_last_7_days,
  ROUND(((files_last_30_days::float / GREATEST(total_files - files_last_30_days, 1)) * 100)::numeric, 1) as monthly_growth_rate,

  -- Recommendations
  CASE 
    WHEN unused_files::float / total_files > 0.2 THEN 'High cleanup potential - consider archiving unused files'
    WHEN cold_storage_bytes::float / total_storage_bytes > 0.5 THEN 'Cold storage optimization recommended'
    WHEN files_last_7_days::float / files_last_30_days > 0.5 THEN 'High recent activity - monitor storage growth'
    ELSE 'File storage appears optimized'
  END as optimization_recommendation

FROM aggregated_analytics;

-- File cleanup and maintenance operations
DELETE FROM files 
WHERE 
  -- Remove temporary files older than 24 hours
  (metadata.category = 'temporary' AND upload_date < CURRENT_TIMESTAMP - INTERVAL '24 hours')

  OR 

  -- Remove unused files older than 1 year with no downloads
  (download_count = 0 AND upload_date < CURRENT_TIMESTAMP - INTERVAL '1 year')

  OR

  -- Remove orphaned file versions (parent file no longer exists)
  (metadata.parent_file_id IS NOT NULL AND 
   metadata.parent_file_id NOT IN (SELECT file_id FROM files WHERE metadata.is_current_version = true));

-- QueryLeaf provides comprehensive GridFS capabilities:
-- 1. SQL-familiar syntax for MongoDB GridFS file storage and management  
-- 2. Advanced file upload with comprehensive metadata and processing options
-- 3. Sophisticated file search with relevance scoring and multi-field filtering
-- 4. Complete file versioning system with history tracking and comparison
-- 5. Real-time file analytics and usage reporting with optimization recommendations
-- 6. Automated file lifecycle management and cleanup operations
-- 7. Integration with MongoDB's native GridFS chunking and streaming capabilities
-- 8. Advanced access control and permission management for file security
-- 9. Performance optimization through intelligent caching and storage distribution
-- 10. Production-ready file management with monitoring, alerts, and maintenance automation

Best Practices for Production GridFS Implementation

File Storage Strategy

Essential principles for effective MongoDB GridFS deployment and management:

  1. Bucket Organization: Design appropriate GridFS buckets for different file types and use cases to optimize performance
  2. Chunk Size Optimization: Configure optimal chunk sizes based on file types and access patterns for storage efficiency
  3. Metadata Design: Implement comprehensive metadata schemas for search, categorization, and lifecycle management
  4. Access Control Integration: Design robust permission systems that integrate with application authentication and authorization
  5. Performance Monitoring: Implement comprehensive monitoring for file access patterns, storage growth, and system performance
  6. Backup and Recovery: Design complete backup strategies that ensure file integrity and availability

Scalability and Performance Optimization

Optimize GridFS deployments for production-scale requirements:

  1. Sharding Strategy: Design appropriate sharding keys for distributed file storage across MongoDB clusters
  2. Index Optimization: Create optimal indexes for file metadata queries and search operations
  3. Caching Implementation: Implement multi-tier caching strategies for frequently accessed files
  4. Content Delivery: Integrate with CDN services for optimal file delivery performance
  5. Storage Optimization: Implement automated archival, compression, and deduplication strategies
  6. Resource Management: Monitor and optimize storage utilization, network bandwidth, and processing resources

Conclusion

MongoDB GridFS provides a comprehensive solution for storing and managing large files within MongoDB applications, offering seamless integration between file storage and document data while supporting advanced features like streaming, versioning, metadata management, and scalable storage patterns. The native MongoDB integration ensures that file storage benefits from the same replication, sharding, and backup capabilities as application data.

Key MongoDB GridFS benefits include:

  • Seamless Integration: Native MongoDB integration with automatic replication, sharding, and backup capabilities
  • Advanced File Management: Comprehensive versioning, metadata extraction, thumbnail generation, and processing pipelines
  • Scalable Architecture: Automatic file chunking and streaming support for files of any size
  • Sophisticated Search: Rich metadata-based search with relevance scoring and advanced filtering capabilities
  • Production Features: Built-in access control, lifecycle management, monitoring, and optimization capabilities
  • SQL Compatibility: Familiar SQL-style file operations through QueryLeaf integration for accessible file management

Whether you're building document management systems, media applications, content platforms, or any application requiring sophisticated file storage, MongoDB GridFS with QueryLeaf's familiar SQL interface provides the foundation for robust, scalable file management.

QueryLeaf Integration: QueryLeaf automatically manages MongoDB GridFS operations while providing SQL-familiar syntax for file upload, download, search, and management. Advanced GridFS patterns, metadata management, and file processing capabilities are seamlessly handled through familiar SQL constructs, making sophisticated file storage both powerful and accessible to SQL-oriented development teams.

The combination of MongoDB's robust GridFS capabilities with SQL-style file operations makes it an ideal platform for applications requiring both advanced file storage and familiar database management patterns, ensuring your file storage solutions can scale efficiently while remaining maintainable and feature-rich as they evolve.

MongoDB Transactions and ACID Compliance: Advanced Multi-Document Operations for Distributed Application Consistency

Modern distributed applications require sophisticated transaction management capabilities that can guarantee data consistency across multiple documents, collections, and database operations while maintaining high performance and availability. Traditional approaches to maintaining consistency in NoSQL systems often involve complex application-level coordination, eventual consistency patterns, or sacrificing atomicity guarantees that become increasingly problematic as business logic complexity grows.

MongoDB's multi-document ACID transactions provide comprehensive support for complex business operations that span multiple documents and collections while maintaining strict consistency guarantees. Unlike traditional NoSQL systems that sacrifice consistency for scalability, MongoDB transactions offer full ACID compliance with distributed transaction support, enabling sophisticated financial applications, inventory management systems, and complex workflow automation that requires atomic operations across multiple data entities.

The Traditional NoSQL Transaction Challenge

Conventional NoSQL transaction approaches suffer from significant limitations for complex business operations:

// Traditional NoSQL approaches - complex application-level coordination and consistency challenges

// Approach 1: Application-level two-phase commit (error-prone and complex)
class TraditionalOrderProcessor {
  constructor(databases) {
    this.userDB = databases.users;
    this.inventoryDB = databases.inventory;
    this.orderDB = databases.orders;
    this.paymentDB = databases.payments;
    this.auditDB = databases.audit;

    // Complex state tracking for manual coordination
    this.pendingTransactions = new Map();
    this.compensationLog = [];
    this.retryQueue = [];
  }

  async processComplexOrder(orderData) {
    const transactionId = require('crypto').randomUUID();
    const operationLog = [];
    let rollbackOperations = [];

    try {
      // Phase 1: Prepare all operations
      console.log('Phase 1: Preparing distributed operations...');

      // Step 1: Validate user account and credit limit
      const user = await this.userDB.findOne({ _id: orderData.userId });
      if (!user) {
        throw new Error('User not found');
      }

      if (user.creditLimit < orderData.totalAmount) {
        throw new Error('Insufficient credit limit');
      }

      // Step 2: Reserve inventory across multiple items
      const inventoryReservations = [];
      const inventoryUpdates = [];

      for (const item of orderData.items) {
        const product = await this.inventoryDB.findOne({ 
          _id: item.productId,
          availableQuantity: { $gte: item.quantity }
        });

        if (!product) {
          // Manual rollback required
          await this.rollbackInventoryReservations(inventoryReservations);
          throw new Error(`Insufficient inventory for product ${item.productId}`);
        }

        // Manual inventory reservation (not atomic)
        const reservationResult = await this.inventoryDB.updateOne(
          { 
            _id: item.productId,
            availableQuantity: { $gte: item.quantity }
          },
          {
            $inc: { 
              availableQuantity: -item.quantity,
              reservedQuantity: item.quantity
            },
            $push: {
              reservations: {
                orderId: transactionId,
                quantity: item.quantity,
                timestamp: new Date(),
                status: 'pending'
              }
            }
          }
        );

        if (reservationResult.modifiedCount === 0) {
          // Race condition occurred, need to rollback
          await this.rollbackInventoryReservations(inventoryReservations);
          throw new Error(`Race condition: inventory changed for product ${item.productId}`);
        }

        inventoryReservations.push({
          productId: item.productId,
          quantity: item.quantity,
          reservationId: `${transactionId}_${item.productId}`
        });

        rollbackOperations.push({
          type: 'inventory_rollback',
          operation: () => this.inventoryDB.updateOne(
            { _id: item.productId },
            {
              $inc: {
                availableQuantity: item.quantity,
                reservedQuantity: -item.quantity
              },
              $pull: {
                reservations: { orderId: transactionId }
              }
            }
          )
        });
      }

      // Step 3: Process payment authorization
      const paymentAuth = await this.processPaymentAuthorization(orderData);
      if (!paymentAuth.success) {
        await this.rollbackInventoryReservations(inventoryReservations);
        throw new Error(`Payment authorization failed: ${paymentAuth.error}`);
      }

      rollbackOperations.push({
        type: 'payment_rollback',
        operation: () => this.voidPaymentAuthorization(paymentAuth.authId)
      });

      // Step 4: Update user account balance and credit
      const userUpdateResult = await this.userDB.updateOne(
        { 
          _id: orderData.userId,
          creditUsed: { $lte: user.creditLimit - orderData.totalAmount }
        },
        {
          $inc: {
            creditUsed: orderData.totalAmount,
            totalOrderValue: orderData.totalAmount,
            orderCount: 1
          },
          $set: {
            lastOrderDate: new Date()
          }
        }
      );

      if (userUpdateResult.modifiedCount === 0) {
        // User account changed during processing
        await this.executeRollbackOperations(rollbackOperations);
        throw new Error('User account state changed during processing');
      }

      rollbackOperations.push({
        type: 'user_rollback', 
        operation: () => this.userDB.updateOne(
          { _id: orderData.userId },
          {
            $inc: {
              creditUsed: -orderData.totalAmount,
              totalOrderValue: -orderData.totalAmount,
              orderCount: -1
            }
          }
        )
      });

      // Phase 2: Commit all operations
      console.log('Phase 2: Committing distributed transaction...');

      // Create the order document
      const orderDocument = {
        _id: transactionId,
        userId: orderData.userId,
        items: orderData.items,
        totalAmount: orderData.totalAmount,
        paymentAuthId: paymentAuth.authId,
        inventoryReservations: inventoryReservations,
        status: 'processing',
        createdAt: new Date(),
        transactionLog: operationLog
      };

      const orderResult = await this.orderDB.insertOne(orderDocument);
      if (!orderResult.insertedId) {
        await this.executeRollbackOperations(rollbackOperations);
        throw new Error('Failed to create order document');
      }

      // Confirm inventory reservations
      for (const reservation of inventoryReservations) {
        await this.inventoryDB.updateOne(
          { 
            _id: reservation.productId,
            'reservations.orderId': transactionId
          },
          {
            $set: {
              'reservations.$.status': 'confirmed',
              'reservations.$.confirmedAt': new Date()
            }
          }
        );
      }

      // Capture payment
      const paymentCapture = await this.capturePayment(paymentAuth.authId);
      if (!paymentCapture.success) {
        await this.executeRollbackOperations(rollbackOperations);
        throw new Error(`Payment capture failed: ${paymentCapture.error}`);
      }

      // Record payment transaction
      await this.paymentDB.insertOne({
        _id: `payment_${transactionId}`,
        orderId: transactionId,
        userId: orderData.userId,
        amount: orderData.totalAmount,
        authId: paymentAuth.authId,
        captureId: paymentCapture.captureId,
        status: 'captured',
        capturedAt: new Date()
      });

      // Update order status
      await this.orderDB.updateOne(
        { _id: transactionId },
        {
          $set: {
            status: 'confirmed',
            confirmedAt: new Date(),
            paymentCaptureId: paymentCapture.captureId
          }
        }
      );

      // Audit log entry
      await this.auditDB.insertOne({
        _id: `audit_${transactionId}`,
        transactionId: transactionId,
        operationType: 'order_processing',
        userId: orderData.userId,
        amount: orderData.totalAmount,
        operations: operationLog,
        status: 'success',
        completedAt: new Date()
      });

      console.log(`Transaction ${transactionId} completed successfully`);
      return {
        success: true,
        transactionId: transactionId,
        orderId: transactionId,
        operationsCompleted: operationLog.length
      };

    } catch (error) {
      console.error(`Transaction ${transactionId} failed:`, error.message);

      // Execute rollback operations in reverse order
      await this.executeRollbackOperations(rollbackOperations.reverse());

      // Log failure for investigation
      await this.auditDB.insertOne({
        _id: `audit_failed_${transactionId}`,
        transactionId: transactionId,
        operationType: 'order_processing',
        userId: orderData.userId,
        amount: orderData.totalAmount,
        error: error.message,
        rollbackOperations: rollbackOperations.length,
        status: 'failed',
        failedAt: new Date()
      });

      return {
        success: false,
        transactionId: transactionId,
        error: error.message,
        rollbacksExecuted: rollbackOperations.length
      };
    }
  }

  async rollbackInventoryReservations(reservations) {
    const rollbackPromises = reservations.map(async (reservation) => {
      try {
        await this.inventoryDB.updateOne(
          { _id: reservation.productId },
          {
            $inc: {
              availableQuantity: reservation.quantity,
              reservedQuantity: -reservation.quantity
            },
            $pull: {
              reservations: { orderId: reservation.reservationId }
            }
          }
        );
      } catch (rollbackError) {
        console.error(`Rollback failed for product ${reservation.productId}:`, rollbackError);
        // In production, this would need sophisticated error handling
        // and potentially manual intervention
      }
    });

    await Promise.allSettled(rollbackPromises);
  }

  async executeRollbackOperations(rollbackOperations) {
    for (const rollback of rollbackOperations) {
      try {
        await rollback.operation();
        console.log(`Rollback completed: ${rollback.type}`);
      } catch (rollbackError) {
        console.error(`Rollback failed: ${rollback.type}`, rollbackError);
        // This is where things get really complicated - failed rollbacks
        // require manual intervention and complex recovery procedures
      }
    }
  }

  async processPaymentAuthorization(orderData) {
    // Simulate payment authorization
    return new Promise((resolve) => {
      setTimeout(() => {
        if (Math.random() > 0.1) { // 90% success rate
          resolve({
            success: true,
            authId: `auth_${require('crypto').randomUUID()}`,
            amount: orderData.totalAmount,
            authorizedAt: new Date()
          });
        } else {
          resolve({
            success: false,
            error: 'Payment authorization declined'
          });
        }
      }, 100);
    });
  }

  async capturePayment(authId) {
    // Simulate payment capture
    return new Promise((resolve) => {
      setTimeout(() => {
        if (Math.random() > 0.05) { // 95% success rate
          resolve({
            success: true,
            captureId: `capture_${require('crypto').randomUUID()}`,
            capturedAt: new Date()
          });
        } else {
          resolve({
            success: false,
            error: 'Payment capture failed'
          });
        }
      }, 150);
    });
  }
}

// Problems with traditional NoSQL transaction approaches:
// 1. Complex application-level coordination requiring extensive error handling
// 2. Race conditions and consistency issues between operations
// 3. Manual rollback implementation prone to failures and partial states
// 4. No atomicity guarantees - partial failures leave system in inconsistent state
// 5. Difficult debugging and troubleshooting of transaction failures
// 6. Poor performance due to multiple round-trips and coordination overhead
// 7. Scalability limitations as transaction complexity increases
// 8. No isolation guarantees - concurrent transactions can interfere
// 9. Limited durability guarantees without complex persistence coordination
// 10. Operational complexity for monitoring and maintaining distributed state

// Approach 2: Eventual consistency with compensation patterns (Saga pattern)
class SagaOrderProcessor {
  constructor(eventStore, commandHandlers) {
    this.eventStore = eventStore;
    this.commandHandlers = commandHandlers;
    this.sagaState = new Map();
  }

  async processOrderSaga(orderData) {
    const sagaId = require('crypto').randomUUID();
    const saga = {
      id: sagaId,
      status: 'started',
      steps: [
        { name: 'validate_user', status: 'pending', compensate: 'none' },
        { name: 'reserve_inventory', status: 'pending', compensate: 'release_inventory' },
        { name: 'process_payment', status: 'pending', compensate: 'refund_payment' },
        { name: 'create_order', status: 'pending', compensate: 'cancel_order' },
        { name: 'update_user_account', status: 'pending', compensate: 'revert_user_account' }
      ],
      currentStep: 0,
      compensationNeeded: false,
      orderData: orderData,
      createdAt: new Date()
    };

    this.sagaState.set(sagaId, saga);

    try {
      await this.executeSagaSteps(saga);
      return { success: true, sagaId: sagaId, status: 'completed' };
    } catch (error) {
      await this.executeCompensation(saga, error);
      return { success: false, sagaId: sagaId, error: error.message, status: 'compensated' };
    }
  }

  async executeSagaSteps(saga) {
    for (let i = saga.currentStep; i < saga.steps.length; i++) {
      const step = saga.steps[i];
      console.log(`Executing saga step: ${step.name}`);

      try {
        const stepResult = await this.executeStep(step.name, saga.orderData);
        step.status = 'completed';
        step.result = stepResult;
        saga.currentStep = i + 1;

        // Save saga state after each step
        await this.saveSagaState(saga);

      } catch (stepError) {
        console.error(`Saga step ${step.name} failed:`, stepError);
        step.status = 'failed';
        step.error = stepError.message;
        saga.compensationNeeded = true;
        throw stepError;
      }
    }

    saga.status = 'completed';
    await this.saveSagaState(saga);
  }

  async executeCompensation(saga, originalError) {
    console.log(`Executing compensation for saga ${saga.id}`);
    saga.status = 'compensating';

    // Execute compensation in reverse order of completed steps
    for (let i = saga.currentStep - 1; i >= 0; i--) {
      const step = saga.steps[i];

      if (step.status === 'completed' && step.compensate !== 'none') {
        try {
          console.log(`Compensating step: ${step.name}`);
          await this.executeCompensation(step.compensate, step.result, saga.orderData);
          step.compensationStatus = 'completed';
        } catch (compensationError) {
          console.error(`Compensation failed for ${step.name}:`, compensationError);
          step.compensationStatus = 'failed';
          step.compensationError = compensationError.message;

          // In a real system, this would require manual intervention
          // or sophisticated retry and escalation mechanisms
        }
      }
    }

    saga.status = 'compensated';
    saga.originalError = originalError.message;
    await this.saveSagaState(saga);
  }

  // Saga pattern problems:
  // 1. Complex state management and coordination across services
  // 2. No isolation - other transactions can see intermediate states
  // 3. Compensation logic complexity increases exponentially with steps
  // 4. Potential for cascading failures during compensation
  // 5. Debugging and troubleshooting distributed saga state is difficult
  // 6. Performance overhead from state persistence and coordination
  // 7. Limited consistency guarantees during saga execution
  // 8. Operational complexity for monitoring and error recovery
  // 9. No built-in support for complex business rules and constraints
  // 10. Scalability challenges as saga complexity and concurrency increase
}

MongoDB provides comprehensive ACID transactions with multi-document support:

// MongoDB Multi-Document ACID Transactions - comprehensive atomic operations with full consistency guarantees
const { MongoClient, ClientSession } = require('mongodb');

const client = new MongoClient('mongodb://localhost:27017');
const db = client.db('ecommerce_platform');

// Advanced MongoDB Transaction Management System
class MongoTransactionManager {
  constructor(db) {
    this.db = db;
    this.collections = {
      users: db.collection('users'),
      products: db.collection('products'),
      inventory: db.collection('inventory'), 
      orders: db.collection('orders'),
      payments: db.collection('payments'),
      audit: db.collection('audit'),
      promotions: db.collection('promotions'),
      loyalty: db.collection('loyalty_points')
    };

    // Transaction configuration
    this.transactionConfig = {
      readConcern: { level: 'snapshot' },
      writeConcern: { w: 'majority', j: true },
      readPreference: 'primary',
      maxTimeMS: 60000, // 1 minute timeout
      maxCommitTimeMS: 30000 // 30 second commit timeout
    };

    this.retryConfig = {
      maxRetries: 3,
      retryDelayMs: 100,
      backoffFactor: 2
    };
  }

  async processComplexOrderTransaction(orderData, options = {}) {
    console.log(`Starting complex order transaction for user: ${orderData.userId}`);

    const session = client.startSession();
    const transactionResults = {
      transactionId: require('crypto').randomUUID(),
      success: false,
      operations: [],
      metrics: {
        startTime: new Date(),
        endTime: null,
        durationMs: 0,
        documentsModified: 0,
        collectionsAffected: 0
      },
      rollbackExecuted: false,
      error: null
    };

    try {
      // Start transaction with ACID guarantees
      await session.withTransaction(async () => {
        console.log('Beginning atomic transaction...');

        // Operation 1: Validate user account and apply business rules
        const userValidation = await this.validateAndUpdateUserAccount(
          orderData.userId, 
          orderData.totalAmount, 
          session,
          transactionResults
        );

        if (!userValidation.valid) {
          throw new Error(`User validation failed: ${userValidation.reason}`);
        }

        // Operation 2: Apply promotional codes and calculate discounts
        const promotionResult = await this.applyPromotionsAndDiscounts(
          orderData,
          userValidation.user,
          session,
          transactionResults
        );

        // Update order total with promotions
        orderData.originalTotal = orderData.totalAmount;
        orderData.totalAmount = promotionResult.finalAmount;
        orderData.discountsApplied = promotionResult.discountsApplied;

        // Operation 3: Reserve inventory with complex allocation logic
        const inventoryReservation = await this.reserveInventoryWithAllocation(
          orderData.items,
          transactionResults.transactionId,
          session,
          transactionResults
        );

        if (!inventoryReservation.success) {
          throw new Error(`Inventory reservation failed: ${inventoryReservation.reason}`);
        }

        // Operation 4: Process payment with fraud detection
        const paymentResult = await this.processPaymentWithFraudDetection(
          orderData,
          userValidation.user,
          session,
          transactionResults
        );

        if (!paymentResult.success) {
          throw new Error(`Payment processing failed: ${paymentResult.reason}`);
        }

        // Operation 5: Create comprehensive order document
        const orderCreation = await this.createComprehensiveOrder(
          orderData,
          userValidation.user,
          inventoryReservation,
          paymentResult,
          promotionResult,
          session,
          transactionResults
        );

        // Operation 6: Update user loyalty points and tier status
        await this.updateUserLoyaltyAndTier(
          orderData.userId,
          orderData.totalAmount,
          orderData.items,
          session,
          transactionResults
        );

        // Operation 7: Create audit trail with comprehensive tracking
        await this.createComprehensiveAuditTrail(
          transactionResults.transactionId,
          orderData,
          userValidation.user,
          paymentResult,
          inventoryReservation,
          promotionResult,
          session,
          transactionResults
        );

        // All operations completed successfully within transaction
        console.log(`Transaction ${transactionResults.transactionId} completed with ${transactionResults.operations.length} operations`);

      }, this.transactionConfig);

      // Transaction committed successfully
      transactionResults.success = true;
      transactionResults.metrics.endTime = new Date();
      transactionResults.metrics.durationMs = transactionResults.metrics.endTime - transactionResults.metrics.startTime;

      console.log(`Order transaction completed successfully in ${transactionResults.metrics.durationMs}ms`);
      console.log(`${transactionResults.metrics.documentsModified} documents modified across ${transactionResults.metrics.collectionsAffected} collections`);

    } catch (error) {
      console.error(`Transaction ${transactionResults.transactionId} failed:`, error.message);
      transactionResults.success = false;
      transactionResults.error = {
        message: error.message,
        code: error.code,
        codeName: error.codeName,
        stack: error.stack
      };
      transactionResults.rollbackExecuted = true;
      transactionResults.metrics.endTime = new Date();
      transactionResults.metrics.durationMs = transactionResults.metrics.endTime - transactionResults.metrics.startTime;

      // MongoDB automatically handles rollback for failed transactions
      console.log(`Automatic rollback executed for transaction ${transactionResults.transactionId}`);

    } finally {
      await session.endSession();
    }

    return transactionResults;
  }

  async validateAndUpdateUserAccount(userId, orderAmount, session, transactionResults) {
    console.log(`Validating user account: ${userId}`);

    const user = await this.collections.users.findOne(
      { _id: userId },
      { session }
    );

    if (!user) {
      return { valid: false, reason: 'User not found' };
    }

    if (user.status !== 'active') {
      return { valid: false, reason: 'User account is not active' };
    }

    // Complex business rules validation
    const availableCredit = user.creditLimit - user.creditUsed;
    const dailySpendingLimit = user.dailySpendingLimit || user.creditLimit * 0.3;
    const todaySpending = user.dailySpending?.find(d => 
      d.date.toDateString() === new Date().toDateString()
    )?.amount || 0;

    if (orderAmount > availableCredit) {
      return { 
        valid: false, 
        reason: `Insufficient credit: available ${availableCredit}, required ${orderAmount}` 
      };
    }

    if (todaySpending + orderAmount > dailySpendingLimit) {
      return { 
        valid: false, 
        reason: `Daily spending limit exceeded: limit ${dailySpendingLimit}, current ${todaySpending}, requested ${orderAmount}` 
      };
    }

    // Update user account within transaction
    const updateResult = await this.collections.users.updateOne(
      { _id: userId },
      {
        $inc: {
          creditUsed: orderAmount,
          totalOrderValue: orderAmount,
          orderCount: 1
        },
        $set: {
          lastOrderDate: new Date(),
          lastActivityAt: new Date()
        },
        $push: {
          dailySpending: {
            $each: [{
              date: new Date(),
              amount: todaySpending + orderAmount
            }],
            $slice: -30 // Keep last 30 days
          }
        }
      },
      { session }
    );

    this.updateTransactionMetrics(transactionResults, 'users', 'validateAndUpdateUserAccount', updateResult);

    return { 
      valid: true, 
      user: user,
      creditUsed: orderAmount,
      remainingCredit: availableCredit - orderAmount
    };
  }

  async applyPromotionsAndDiscounts(orderData, user, session, transactionResults) {
    console.log('Applying promotions and discounts...');

    let finalAmount = orderData.totalAmount;
    let discountsApplied = [];

    // Find applicable promotions
    const applicablePromotions = await this.collections.promotions.find({
      status: 'active',
      startDate: { $lte: new Date() },
      endDate: { $gte: new Date() },
      $or: [
        { applicableToUsers: user._id },
        { applicableToUserTiers: user.tier },
        { applicableToAll: true }
      ]
    }, { session }).toArray();

    for (const promotion of applicablePromotions) {
      let discountAmount = 0;
      let applicable = false;

      // Validate promotion conditions
      if (promotion.minimumOrderAmount && orderData.totalAmount < promotion.minimumOrderAmount) {
        continue;
      }

      if (promotion.applicableProducts && promotion.applicableProducts.length > 0) {
        const hasApplicableProducts = orderData.items.some(item => 
          promotion.applicableProducts.includes(item.productId)
        );
        if (!hasApplicableProducts) continue;
      }

      // Calculate discount based on promotion type
      switch (promotion.type) {
        case 'percentage':
          discountAmount = finalAmount * (promotion.discountPercentage / 100);
          if (promotion.maxDiscount) {
            discountAmount = Math.min(discountAmount, promotion.maxDiscount);
          }
          applicable = true;
          break;

        case 'fixed_amount':
          discountAmount = Math.min(promotion.discountAmount, finalAmount);
          applicable = true;
          break;

        case 'buy_x_get_y':
          const qualifyingItems = orderData.items.filter(item => 
            promotion.buyProducts.includes(item.productId)
          );
          const totalQualifyingQuantity = qualifyingItems.reduce((sum, item) => sum + item.quantity, 0);

          if (totalQualifyingQuantity >= promotion.buyQuantity) {
            const freeQuantity = Math.floor(totalQualifyingQuantity / promotion.buyQuantity) * promotion.getQuantity;
            const averagePrice = qualifyingItems.reduce((sum, item) => sum + item.price, 0) / qualifyingItems.length;
            discountAmount = freeQuantity * averagePrice;
            applicable = true;
          }
          break;
      }

      if (applicable && discountAmount > 0) {
        finalAmount -= discountAmount;
        discountsApplied.push({
          promotionId: promotion._id,
          promotionName: promotion.name,
          discountAmount: discountAmount,
          appliedAt: new Date()
        });

        // Update promotion usage
        await this.collections.promotions.updateOne(
          { _id: promotion._id },
          {
            $inc: { usageCount: 1 },
            $push: {
              recentUsage: {
                userId: user._id,
                orderId: transactionResults.transactionId,
                discountAmount: discountAmount,
                usedAt: new Date()
              }
            }
          },
          { session }
        );

        this.updateTransactionMetrics(transactionResults, 'promotions', 'applyPromotionsAndDiscounts');
      }
    }

    console.log(`Applied ${discountsApplied.length} promotions, total discount: ${orderData.totalAmount - finalAmount}`);

    return {
      finalAmount: Math.max(finalAmount, 0), // Ensure non-negative
      discountsApplied: discountsApplied,
      totalDiscount: orderData.totalAmount - finalAmount
    };
  }

  async reserveInventoryWithAllocation(orderItems, transactionId, session, transactionResults) {
    console.log(`Reserving inventory for ${orderItems.length} items...`);

    const reservationResults = [];
    const allocationStrategy = 'fifo'; // First-In-First-Out allocation

    for (const item of orderItems) {
      // Find available inventory with complex allocation logic
      const inventoryRecords = await this.collections.inventory.find({
        productId: item.productId,
        availableQuantity: { $gt: 0 },
        status: 'active'
      }, { session })
      .sort({ createdAt: 1 }) // FIFO allocation
      .toArray();

      let remainingQuantity = item.quantity;
      const allocatedFrom = [];

      for (const inventoryRecord of inventoryRecords) {
        if (remainingQuantity <= 0) break;

        const allocateQuantity = Math.min(remainingQuantity, inventoryRecord.availableQuantity);

        // Reserve inventory from this record
        const reservationResult = await this.collections.inventory.updateOne(
          { 
            _id: inventoryRecord._id,
            availableQuantity: { $gte: allocateQuantity }
          },
          {
            $inc: { 
              availableQuantity: -allocateQuantity,
              reservedQuantity: allocateQuantity
            },
            $push: {
              reservations: {
                reservationId: `${transactionId}_${item.productId}_${inventoryRecord._id}`,
                orderId: transactionId,
                quantity: allocateQuantity,
                reservedAt: new Date(),
                expiresAt: new Date(Date.now() + 30 * 60 * 1000), // 30 minutes
                status: 'active'
              }
            }
          },
          { session }
        );

        if (reservationResult.modifiedCount === 1) {
          allocatedFrom.push({
            inventoryId: inventoryRecord._id,
            warehouseLocation: inventoryRecord.location,
            quantity: allocateQuantity,
            unitCost: inventoryRecord.unitCost
          });
          remainingQuantity -= allocateQuantity;

          this.updateTransactionMetrics(transactionResults, 'inventory', 'reserveInventoryWithAllocation', reservationResult);
        }
      }

      if (remainingQuantity > 0) {
        return {
          success: false,
          reason: `Insufficient inventory for product ${item.productId}: requested ${item.quantity}, available ${item.quantity - remainingQuantity}`
        };
      }

      reservationResults.push({
        productId: item.productId,
        requestedQuantity: item.quantity,
        allocatedFrom: allocatedFrom,
        totalCost: allocatedFrom.reduce((sum, alloc) => sum + (alloc.quantity * alloc.unitCost), 0)
      });
    }

    console.log(`Successfully reserved inventory for all ${orderItems.length} items`);

    return {
      success: true,
      reservationId: transactionId,
      reservations: reservationResults,
      totalReservedItems: reservationResults.reduce((sum, res) => sum + res.requestedQuantity, 0)
    };
  }

  async processPaymentWithFraudDetection(orderData, user, session, transactionResults) {
    console.log(`Processing payment with fraud detection for order amount: ${orderData.totalAmount}`);

    // Fraud detection analysis within transaction
    const fraudScore = await this.calculateFraudScore(orderData, user, session);

    if (fraudScore > 0.8) {
      return {
        success: false,
        reason: `Transaction flagged for fraud (score: ${fraudScore})`,
        fraudScore: fraudScore
      };
    }

    // Process payment (in real system, this would integrate with payment gateway)
    const paymentRecord = {
      _id: `payment_${transactionResults.transactionId}`,
      orderId: transactionResults.transactionId,
      userId: user._id,
      amount: orderData.totalAmount,
      originalAmount: orderData.originalTotal || orderData.totalAmount,
      paymentMethod: orderData.paymentMethod,
      fraudScore: fraudScore,

      // Payment processing details
      authorizationId: `auth_${require('crypto').randomUUID()}`,
      captureId: `capture_${require('crypto').randomUUID()}`,

      status: 'completed',
      processedAt: new Date(),

      // Enhanced payment metadata
      riskAssessment: {
        score: fraudScore,
        factors: await this.getFraudFactors(orderData, user),
        recommendation: fraudScore > 0.5 ? 'review' : 'approve'
      },

      processingFees: {
        gatewayFee: orderData.totalAmount * 0.029 + 0.30, // Typical payment gateway fee
        fraudProtectionFee: 0.05
      }
    };

    const insertResult = await this.collections.payments.insertOne(paymentRecord, { session });

    this.updateTransactionMetrics(transactionResults, 'payments', 'processPaymentWithFraudDetection', insertResult);

    console.log(`Payment processed successfully: ${paymentRecord._id}`);

    return {
      success: true,
      paymentId: paymentRecord._id,
      authorizationId: paymentRecord.authorizationId,
      captureId: paymentRecord.captureId,
      fraudScore: fraudScore,
      processingFees: paymentRecord.processingFees
    };
  }

  async createComprehensiveOrder(orderData, user, inventoryReservation, paymentResult, promotionResult, session, transactionResults) {
    console.log('Creating comprehensive order document...');

    const orderDocument = {
      _id: transactionResults.transactionId,
      orderNumber: `ORD-${Date.now()}-${Math.random().toString(36).substr(2, 6).toUpperCase()}`,

      // Customer information
      customer: {
        userId: user._id,
        email: user.email,
        tier: user.tier,
        isReturningCustomer: user.orderCount > 0
      },

      // Order details
      items: orderData.items.map(item => ({
        ...item,
        allocation: inventoryReservation.reservations.find(r => r.productId === item.productId)?.allocatedFrom || []
      })),

      // Financial details
      pricing: {
        subtotal: orderData.originalTotal || orderData.totalAmount,
        discounts: promotionResult.discountsApplied || [],
        totalDiscount: promotionResult.totalDiscount || 0,
        finalAmount: orderData.totalAmount,
        tax: orderData.tax || 0,
        shipping: orderData.shipping || 0,
        total: orderData.totalAmount
      },

      // Payment information
      payment: {
        paymentId: paymentResult.paymentId,
        method: orderData.paymentMethod,
        status: 'completed',
        fraudScore: paymentResult.fraudScore,
        processedAt: new Date()
      },

      // Inventory allocation
      inventory: {
        reservationId: inventoryReservation.reservationId,
        totalItemsReserved: inventoryReservation.totalReservedItems,
        reservationDetails: inventoryReservation.reservations
      },

      // Order lifecycle
      status: 'confirmed',
      lifecycle: {
        createdAt: new Date(),
        confirmedAt: new Date(),
        estimatedFulfillmentDate: new Date(Date.now() + 2 * 24 * 60 * 60 * 1000), // 2 days
        estimatedDeliveryDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000) // 1 week
      },

      // Shipping information
      shipping: {
        address: orderData.shippingAddress,
        method: orderData.shippingMethod || 'standard',
        trackingNumber: null, // Will be updated when shipped
        carrier: orderData.carrier || 'fedex'
      },

      // Transaction metadata
      transaction: {
        transactionId: transactionResults.transactionId,
        sessionId: session.id ? session.id.toString() : null,
        source: orderData.source || 'web',
        channel: orderData.channel || 'direct'
      }
    };

    const insertResult = await this.collections.orders.insertOne(orderDocument, { session });

    this.updateTransactionMetrics(transactionResults, 'orders', 'createComprehensiveOrder', insertResult);

    console.log(`Order created successfully: ${orderDocument.orderNumber}`);

    return orderDocument;
  }

  async updateUserLoyaltyAndTier(userId, orderAmount, orderItems, session, transactionResults) {
    console.log(`Updating loyalty points and tier for user: ${userId}`);

    // Calculate loyalty points based on complex rules
    const basePoints = Math.floor(orderAmount); // 1 point per dollar
    const bonusPoints = this.calculateBonusPoints(orderItems, orderAmount);
    const totalPoints = basePoints + bonusPoints;

    // Update loyalty points
    const loyaltyUpdate = await this.collections.loyalty.updateOne(
      { userId: userId },
      {
        $inc: {
          totalPointsEarned: totalPoints,
          availablePoints: totalPoints,
          lifetimeValue: orderAmount
        },
        $push: {
          pointsHistory: {
            orderId: transactionResults.transactionId,
            pointsEarned: totalPoints,
            reason: 'order_purchase',
            earnedAt: new Date()
          }
        },
        $set: {
          lastActivityAt: new Date()
        }
      },
      { 
        upsert: true,
        session 
      }
    );

    // Check for tier upgrades
    const loyaltyRecord = await this.collections.loyalty.findOne(
      { userId: userId },
      { session }
    );

    if (loyaltyRecord) {
      const newTier = this.calculateUserTier(loyaltyRecord.lifetimeValue, loyaltyRecord.totalPointsEarned);

      if (newTier !== loyaltyRecord.currentTier) {
        await this.collections.users.updateOne(
          { _id: userId },
          {
            $set: { tier: newTier },
            $push: {
              tierHistory: {
                previousTier: loyaltyRecord.currentTier,
                newTier: newTier,
                upgradedAt: new Date(),
                triggeredBy: transactionResults.transactionId
              }
            }
          },
          { session }
        );

        await this.collections.loyalty.updateOne(
          { userId: userId },
          { $set: { currentTier: newTier } },
          { session }
        );
      }
    }

    this.updateTransactionMetrics(transactionResults, 'loyalty', 'updateUserLoyaltyAndTier', loyaltyUpdate);

    console.log(`Awarded ${totalPoints} loyalty points to user ${userId}`);

    return {
      pointsAwarded: totalPoints,
      basePoints: basePoints,
      bonusPoints: bonusPoints,
      newTier: loyaltyRecord?.currentTier || 'bronze'
    };
  }

  async createComprehensiveAuditTrail(transactionId, orderData, user, paymentResult, inventoryReservation, promotionResult, session, transactionResults) {
    console.log('Creating comprehensive audit trail...');

    const auditRecord = {
      _id: `audit_${transactionId}`,
      transactionId: transactionId,
      auditType: 'order_processing',

      // Transaction context
      context: {
        userId: user._id,
        userEmail: user.email,
        userTier: user.tier,
        sessionId: session.id ? session.id.toString() : null,
        source: orderData.source || 'web',
        userAgent: orderData.userAgent,
        ipAddress: orderData.ipAddress
      },

      // Detailed operation log
      operations: transactionResults.operations.map(op => ({
        ...op,
        timestamp: new Date()
      })),

      // Financial audit trail
      financial: {
        originalAmount: orderData.originalTotal || orderData.totalAmount,
        finalAmount: orderData.totalAmount,
        discountsApplied: promotionResult.discountsApplied || [],
        totalDiscount: promotionResult.totalDiscount || 0,
        paymentMethod: orderData.paymentMethod,
        fraudScore: paymentResult.fraudScore,
        processingFees: paymentResult.processingFees
      },

      // Inventory audit trail
      inventory: {
        reservationId: inventoryReservation.reservationId,
        itemsReserved: inventoryReservation.totalReservedItems,
        allocationDetails: inventoryReservation.reservations
      },

      // Compliance and regulatory data
      compliance: {
        dataProcessingConsent: orderData.dataProcessingConsent || false,
        marketingConsent: orderData.marketingConsent || false,
        privacyPolicyVersion: orderData.privacyPolicyVersion || '1.0',
        termsOfServiceVersion: orderData.termsOfServiceVersion || '1.0'
      },

      // Transaction metrics
      performance: {
        transactionDurationMs: transactionResults.metrics.durationMs || 0,
        documentsModified: transactionResults.metrics.documentsModified,
        collectionsAffected: transactionResults.metrics.collectionsAffected,
        operationsExecuted: transactionResults.operations.length
      },

      // Audit metadata
      auditedAt: new Date(),
      retentionDate: new Date(Date.now() + 7 * 365 * 24 * 60 * 60 * 1000), // 7 years
      status: 'completed'
    };

    const insertResult = await this.collections.audit.insertOne(auditRecord, { session });

    this.updateTransactionMetrics(transactionResults, 'audit', 'createComprehensiveAuditTrail', insertResult);

    console.log(`Audit trail created: ${auditRecord._id}`);

    return auditRecord;
  }

  // Helper methods for transaction processing

  async calculateFraudScore(orderData, user, session) {
    // Simplified fraud scoring algorithm
    let fraudScore = 0.0;

    // Velocity checks
    const recentOrderCount = await this.collections.orders.countDocuments({
      'customer.userId': user._id,
      'lifecycle.createdAt': { $gte: new Date(Date.now() - 24 * 60 * 60 * 1000) }
    }, { session });

    if (recentOrderCount > 5) fraudScore += 0.3;

    // Amount-based risk
    if (orderData.totalAmount > user.averageOrderValue * 3) {
      fraudScore += 0.2;
    }

    // Time-based patterns
    const hour = new Date().getHours();
    if (hour >= 2 && hour <= 6) fraudScore += 0.1; // Unusual hours

    // Geographic risk (simplified)
    if (orderData.ipCountry !== user.country) {
      fraudScore += 0.15;
    }

    return Math.min(fraudScore, 1.0);
  }

  async getFraudFactors(orderData, user) {
    return [
      { factor: 'velocity_check', weight: 0.3 },
      { factor: 'amount_anomaly', weight: 0.2 },
      { factor: 'time_pattern', weight: 0.1 },
      { factor: 'geographic_risk', weight: 0.15 }
    ];
  }

  calculateBonusPoints(orderItems, orderAmount) {
    let bonusPoints = 0;

    // Category-based bonus points
    for (const item of orderItems) {
      if (item.category === 'electronics') bonusPoints += item.quantity * 2;
      else if (item.category === 'premium') bonusPoints += item.quantity * 3;
    }

    // Order size bonus
    if (orderAmount > 500) bonusPoints += 50;
    else if (orderAmount > 200) bonusPoints += 20;

    return bonusPoints;
  }

  calculateUserTier(lifetimeValue, totalPoints) {
    if (lifetimeValue > 10000 && totalPoints > 5000) return 'platinum';
    else if (lifetimeValue > 5000 && totalPoints > 2500) return 'gold';
    else if (lifetimeValue > 1000 && totalPoints > 500) return 'silver';
    else return 'bronze';
  }

  updateTransactionMetrics(transactionResults, collection, operation, result = {}) {
    transactionResults.operations.push({
      collection: collection,
      operation: operation,
      documentsModified: result.modifiedCount || result.insertedCount || result.upsertedCount || 1,
      timestamp: new Date()
    });

    if (result.modifiedCount || result.insertedCount || result.upsertedCount) {
      transactionResults.metrics.documentsModified += result.modifiedCount || result.insertedCount || result.upsertedCount;
    }

    const uniqueCollections = new Set(transactionResults.operations.map(op => op.collection));
    transactionResults.metrics.collectionsAffected = uniqueCollections.size;
  }

  // Advanced transaction patterns and error handling

  async executeWithRetry(transactionFunction, maxRetries = 3) {
    let lastError;

    for (let attempt = 1; attempt <= maxRetries; attempt++) {
      try {
        return await transactionFunction();
      } catch (error) {
        lastError = error;

        // Check if error is retryable
        if (this.isRetryableError(error) && attempt < maxRetries) {
          const delay = this.retryConfig.retryDelayMs * Math.pow(this.retryConfig.backoffFactor, attempt - 1);
          console.log(`Transaction attempt ${attempt} failed, retrying in ${delay}ms: ${error.message}`);
          await new Promise(resolve => setTimeout(resolve, delay));
          continue;
        }

        throw error;
      }
    }

    throw lastError;
  }

  isRetryableError(error) {
    // MongoDB transient transaction errors that can be retried
    const retryableErrorCodes = [
      'TransientTransactionError',
      'UnknownTransactionCommitResult',
      'WriteConflict',
      'LockTimeout'
    ];

    return error.hasErrorLabel && retryableErrorCodes.some(label => error.hasErrorLabel(label));
  }

  async getTransactionStatus(transactionId) {
    // Check transaction completion status across collections
    const collections = ['orders', 'payments', 'audit'];
    const status = {};

    for (const collectionName of collections) {
      const collection = this.collections[collectionName];
      const document = await collection.findOne({ 
        $or: [
          { _id: transactionId },
          { transactionId: transactionId },
          { orderId: transactionId }
        ]
      });

      status[collectionName] = document ? 'completed' : 'missing';
    }

    return status;
  }

  async close() {
    // Close database connections
    if (client) {
      await client.close();
    }
  }
}

// Benefits of MongoDB Multi-Document ACID Transactions:
// - Full ACID compliance with automatic rollback on transaction failure
// - Multi-document atomicity across collections within single database
// - Strong consistency guarantees with configurable read and write concerns
// - Built-in retry logic for transient errors and network issues
// - Automatic deadlock detection and resolution
// - Snapshot isolation preventing dirty reads and write conflicts
// - Comprehensive transaction state management without application complexity
// - Performance optimization through write batching and connection pooling
// - Cross-shard transaction support in sharded environments
// - SQL-compatible transaction management through QueryLeaf integration

module.exports = {
  MongoTransactionManager
};

Understanding MongoDB Transaction Architecture

Advanced Transaction Patterns and Error Handling

Implement sophisticated transaction management for production applications:

// Production-ready transaction patterns with advanced error handling and monitoring
class ProductionTransactionManager extends MongoTransactionManager {
  constructor(db, config = {}) {
    super(db);

    this.productionConfig = {
      ...config,
      transactionTimeoutMs: config.transactionTimeoutMs || 60000,
      maxConcurrentTransactions: config.maxConcurrentTransactions || 100,
      deadlockDetectionEnabled: true,
      performanceMonitoringEnabled: true,
      automaticRetryEnabled: true
    };

    this.activeTransactions = new Map();
    this.transactionMetrics = new Map();
    this.deadlockDetector = new DeadlockDetector();
  }

  async executeBusinessTransaction(transactionType, transactionData, options = {}) {
    console.log(`Executing ${transactionType} business transaction...`);

    const transactionContext = {
      id: require('crypto').randomUUID(),
      type: transactionType,
      data: transactionData,
      options: options,
      startTime: new Date(),
      status: 'started',
      retryCount: 0,
      operations: [],
      checkpoints: []
    };

    // Register active transaction
    this.activeTransactions.set(transactionContext.id, transactionContext);

    try {
      // Execute transaction with comprehensive error handling
      const result = await this.executeWithComprehensiveRetry(async () => {
        return await this.executeTransactionByType(transactionContext);
      }, transactionContext);

      transactionContext.status = 'completed';
      transactionContext.endTime = new Date();
      transactionContext.durationMs = transactionContext.endTime - transactionContext.startTime;

      // Record performance metrics
      await this.recordTransactionMetrics(transactionContext, result);

      console.log(`Transaction ${transactionContext.id} completed in ${transactionContext.durationMs}ms`);
      return result;

    } catch (error) {
      transactionContext.status = 'failed';
      transactionContext.endTime = new Date();
      transactionContext.error = error;

      // Record failure metrics
      await this.recordTransactionFailure(transactionContext, error);

      throw error;
    } finally {
      // Clean up active transaction
      this.activeTransactions.delete(transactionContext.id);
    }
  }

  async executeTransactionByType(transactionContext) {
    const { type, data, options } = transactionContext;

    switch (type) {
      case 'order_processing':
        return await this.processComplexOrderTransaction(data, options);

      case 'inventory_transfer':
        return await this.executeInventoryTransfer(data, transactionContext);

      case 'bulk_user_update':
        return await this.executeBulkUserUpdate(data, transactionContext);

      case 'financial_reconciliation':
        return await this.executeFinancialReconciliation(data, transactionContext);

      default:
        throw new Error(`Unknown transaction type: ${type}`);
    }
  }

  async executeInventoryTransfer(transferData, transactionContext) {
    const session = client.startSession();
    const transferResult = {
      transferId: transactionContext.id,
      sourceWarehouse: transferData.sourceWarehouse,
      targetWarehouse: transferData.targetWarehouse,
      itemsTransferred: [],
      success: false
    };

    try {
      await session.withTransaction(async () => {
        // Validate source warehouse inventory
        for (const item of transferData.items) {
          const sourceInventory = await this.collections.inventory.findOne({
            warehouseId: transferData.sourceWarehouse,
            productId: item.productId,
            availableQuantity: { $gte: item.quantity }
          }, { session });

          if (!sourceInventory) {
            throw new Error(`Insufficient inventory in source warehouse for product ${item.productId}`);
          }

          // Remove from source warehouse
          await this.collections.inventory.updateOne(
            { 
              _id: sourceInventory._id,
              availableQuantity: { $gte: item.quantity }
            },
            {
              $inc: { 
                availableQuantity: -item.quantity,
                transferOutQuantity: item.quantity
              },
              $push: {
                transferHistory: {
                  transferId: transactionContext.id,
                  type: 'outbound',
                  quantity: item.quantity,
                  targetWarehouse: transferData.targetWarehouse,
                  transferredAt: new Date()
                }
              }
            },
            { session }
          );

          // Add to target warehouse
          await this.collections.inventory.updateOne(
            {
              warehouseId: transferData.targetWarehouse,
              productId: item.productId
            },
            {
              $inc: { 
                availableQuantity: item.quantity,
                transferInQuantity: item.quantity
              },
              $push: {
                transferHistory: {
                  transferId: transactionContext.id,
                  type: 'inbound',
                  quantity: item.quantity,
                  sourceWarehouse: transferData.sourceWarehouse,
                  transferredAt: new Date()
                }
              }
            },
            { 
              upsert: true,
              session 
            }
          );

          transferResult.itemsTransferred.push({
            productId: item.productId,
            quantity: item.quantity,
            transferredAt: new Date()
          });
        }

        // Create transfer record
        await this.collections.transfers.insertOne({
          _id: transactionContext.id,
          sourceWarehouse: transferData.sourceWarehouse,
          targetWarehouse: transferData.targetWarehouse,
          items: transferResult.itemsTransferred,
          status: 'completed',
          transferredAt: new Date(),
          transferredBy: transferData.transferredBy
        }, { session });

      }, this.transactionConfig);

      transferResult.success = true;
      return transferResult;

    } finally {
      await session.endSession();
    }
  }

  async executeBulkUserUpdate(updateData, transactionContext) {
    const session = client.startSession();
    const updateResult = {
      updateId: transactionContext.id,
      usersUpdated: 0,
      updatesFailed: 0,
      success: false
    };

    try {
      await session.withTransaction(async () => {
        const bulkOperations = [];

        // Build bulk operations
        for (const userUpdate of updateData.updates) {
          bulkOperations.push({
            updateOne: {
              filter: { _id: userUpdate.userId },
              update: {
                $set: userUpdate.updates,
                $push: {
                  updateHistory: {
                    updateId: transactionContext.id,
                    updates: userUpdate.updates,
                    updatedAt: new Date(),
                    updatedBy: updateData.updatedBy
                  }
                }
              }
            }
          });
        }

        // Execute bulk operation within transaction
        const bulkResult = await this.collections.users.bulkWrite(
          bulkOperations,
          { session, ordered: false }
        );

        updateResult.usersUpdated = bulkResult.modifiedCount;
        updateResult.updatesFailed = updateData.updates.length - bulkResult.modifiedCount;

        // Log bulk update
        await this.collections.bulk_operations.insertOne({
          _id: transactionContext.id,
          operationType: 'bulk_user_update',
          targetCount: updateData.updates.length,
          successCount: bulkResult.modifiedCount,
          failureCount: updateResult.updatesFailed,
          executedAt: new Date(),
          executedBy: updateData.updatedBy
        }, { session });

      }, this.transactionConfig);

      updateResult.success = true;
      return updateResult;

    } finally {
      await session.endSession();
    }
  }

  async executeWithComprehensiveRetry(transactionFunction, transactionContext) {
    let lastError;
    const maxRetries = this.productionConfig.maxRetries || 3;

    for (let attempt = 1; attempt <= maxRetries; attempt++) {
      try {
        transactionContext.retryCount = attempt - 1;
        return await transactionFunction();
      } catch (error) {
        lastError = error;

        // Analyze error and determine retry strategy
        const retryDecision = await this.analyzeErrorForRetry(error, attempt, maxRetries, transactionContext);

        if (retryDecision.shouldRetry) {
          console.log(`Transaction ${transactionContext.id} attempt ${attempt} failed, retrying: ${error.message}`);
          await this.executeRetryDelay(retryDecision.delayMs);
          continue;
        }

        // Error is not retryable or max retries reached
        break;
      }
    }

    // All retries exhausted
    console.error(`Transaction ${transactionContext.id} failed after ${maxRetries} attempts`);
    throw lastError;
  }

  async analyzeErrorForRetry(error, attempt, maxRetries, transactionContext) {
    const retryableErrors = [
      'TransientTransactionError',
      'UnknownTransactionCommitResult',
      'WriteConflict',
      'TemporarilyUnavailable'
    ];

    const isTransientError = error.hasErrorLabel && 
      retryableErrors.some(label => error.hasErrorLabel(label));

    const isTimeoutError = error.code === 50 || error.codeName === 'MaxTimeMSExpired';
    const isNetworkError = error.name === 'MongoNetworkError';

    // Check for deadlock
    const isDeadlock = await this.deadlockDetector.isDeadlock(error, transactionContext);
    if (isDeadlock) {
      await this.resolveDeadlock(transactionContext);
    }

    const shouldRetry = (isTransientError || isTimeoutError || isNetworkError || isDeadlock) && 
                       attempt < maxRetries;

    let delayMs = 100;
    if (shouldRetry) {
      // Exponential backoff with jitter
      const baseDelay = this.retryConfig.retryDelayMs || 100;
      const backoffFactor = this.retryConfig.backoffFactor || 2;
      delayMs = baseDelay * Math.pow(backoffFactor, attempt - 1);

      // Add jitter to prevent thundering herd
      delayMs += Math.random() * 50;
    }

    return {
      shouldRetry: shouldRetry,
      delayMs: delayMs,
      errorType: isTransientError ? 'transient' : 
                isTimeoutError ? 'timeout' : 
                isNetworkError ? 'network' : 
                isDeadlock ? 'deadlock' : 'permanent'
    };
  }

  async executeRetryDelay(delayMs) {
    await new Promise(resolve => setTimeout(resolve, delayMs));
  }

  async recordTransactionMetrics(transactionContext, result) {
    const metrics = {
      transactionId: transactionContext.id,
      transactionType: transactionContext.type,
      durationMs: transactionContext.durationMs,
      retryCount: transactionContext.retryCount,
      operationCount: transactionContext.operations.length,
      documentsModified: result.metrics?.documentsModified || 0,
      collectionsAffected: result.metrics?.collectionsAffected || 0,
      success: true,
      recordedAt: new Date()
    };

    await this.collections.transaction_metrics.insertOne(metrics);

    // Update running averages
    this.updateRunningMetrics(transactionContext.type, metrics);
  }

  async recordTransactionFailure(transactionContext, error) {
    const failureMetrics = {
      transactionId: transactionContext.id,
      transactionType: transactionContext.type,
      durationMs: transactionContext.endTime - transactionContext.startTime,
      retryCount: transactionContext.retryCount,
      errorType: error.name,
      errorCode: error.code,
      errorMessage: error.message,
      success: false,
      recordedAt: new Date()
    };

    await this.collections.transaction_failures.insertOne(failureMetrics);
  }

  updateRunningMetrics(transactionType, metrics) {
    if (!this.transactionMetrics.has(transactionType)) {
      this.transactionMetrics.set(transactionType, {
        totalTransactions: 0,
        totalDurationMs: 0,
        successfulTransactions: 0,
        averageDurationMs: 0
      });
    }

    const typeMetrics = this.transactionMetrics.get(transactionType);
    typeMetrics.totalTransactions++;
    typeMetrics.totalDurationMs += metrics.durationMs;

    if (metrics.success) {
      typeMetrics.successfulTransactions++;
    }

    typeMetrics.averageDurationMs = typeMetrics.totalDurationMs / typeMetrics.totalTransactions;
  }

  getTransactionMetrics(transactionType = null) {
    if (transactionType) {
      return this.transactionMetrics.get(transactionType) || null;
    }

    return Object.fromEntries(this.transactionMetrics);
  }

  async resolveDeadlock(transactionContext) {
    console.log(`Resolving deadlock for transaction ${transactionContext.id}`);

    // Implement deadlock resolution strategy
    // This could involve backing off, reordering operations, or other strategies
    const delayMs = Math.random() * 1000; // Random delay to break deadlock
    await this.executeRetryDelay(delayMs);
  }
}

// Deadlock detection system
class DeadlockDetector {
  constructor() {
    this.waitForGraph = new Map();
    this.transactionLocks = new Map();
  }

  async isDeadlock(error, transactionContext) {
    // Simplified deadlock detection based on error patterns
    const deadlockIndicators = [
      'LockTimeout',
      'WriteConflict', 
      'DeadlockDetected'
    ];

    return error.codeName && deadlockIndicators.includes(error.codeName);
  }

  async detectDeadlockCycle(transactionId) {
    // Implement cycle detection in wait-for graph
    // This is a simplified implementation
    const visited = new Set();
    const recursionStack = new Set();

    const hasCycle = (node) => {
      visited.add(node);
      recursionStack.add(node);

      const dependencies = this.waitForGraph.get(node) || [];
      for (const dependency of dependencies) {
        if (!visited.has(dependency)) {
          if (hasCycle(dependency)) return true;
        } else if (recursionStack.has(dependency)) {
          return true;
        }
      }

      recursionStack.delete(node);
      return false;
    };

    return hasCycle(transactionId);
  }
}

SQL-Style Transaction Management with QueryLeaf

QueryLeaf provides familiar SQL syntax for MongoDB transaction management and ACID operations:

-- QueryLeaf transaction management with SQL-familiar syntax

-- Begin complex multi-document transaction with ACID guarantees
BEGIN TRANSACTION order_processing WITH (
  isolation_level = 'snapshot',
  write_concern = { w = 'majority', j = true },
  read_concern = { level = 'majority' },
  timeout = '60 seconds',
  retry_policy = {
    max_attempts = 3,
    backoff_strategy = 'exponential',
    base_delay = '100ms'
  }
);

-- Transaction Operation 1: Validate and update user account
UPDATE users 
SET 
  credit_used = credit_used + @order_total,
  total_order_value = total_order_value + @order_total,
  order_count = order_count + 1,
  last_order_date = CURRENT_TIMESTAMP,
  daily_spending = ARRAY_APPEND(
    daily_spending,
    DOCUMENT(
      'date', CURRENT_DATE,
      'amount', @order_total
    )
  )
WHERE _id = @user_id 
  AND credit_limit - credit_used >= @order_total
  AND (
    SELECT amount 
    FROM UNNEST(daily_spending) AS ds 
    WHERE ds.date = CURRENT_DATE
  ) + @order_total <= daily_spending_limit;

-- Verify user update succeeded
IF @@ROWCOUNT = 0 THEN
  ROLLBACK TRANSACTION;
  THROW 'INSUFFICIENT_CREDIT', 'User does not have sufficient credit or daily limit exceeded';
END IF;

-- Transaction Operation 2: Apply promotions and calculate discounts
WITH applicable_promotions AS (
  SELECT 
    p._id as promotion_id,
    p.name as promotion_name,
    p.type as discount_type,
    p.discount_percentage,
    p.discount_amount,
    p.max_discount,

    -- Calculate discount amount based on promotion type
    CASE p.type
      WHEN 'percentage' THEN 
        LEAST(@order_total * p.discount_percentage / 100, COALESCE(p.max_discount, @order_total))
      WHEN 'fixed_amount' THEN 
        LEAST(p.discount_amount, @order_total)
      ELSE 0
    END as calculated_discount

  FROM promotions p
  WHERE p.status = 'active'
    AND p.start_date <= CURRENT_TIMESTAMP
    AND p.end_date >= CURRENT_TIMESTAMP
    AND (@order_total >= p.minimum_order_amount OR p.minimum_order_amount IS NULL)
    AND (
      p.applicable_to_all = true OR
      @user_id = ANY(p.applicable_to_users) OR
      @user_tier = ANY(p.applicable_to_user_tiers)
    )
  ORDER BY calculated_discount DESC
  LIMIT 3  -- Apply maximum 3 promotions
)

UPDATE promotions 
SET 
  usage_count = usage_count + 1,
  recent_usage = ARRAY_APPEND(
    recent_usage,
    DOCUMENT(
      'user_id', @user_id,
      'order_id', @transaction_id,
      'discount_amount', ap.calculated_discount,
      'used_at', CURRENT_TIMESTAMP
    )
  )
FROM applicable_promotions ap
WHERE promotions._id = ap.promotion_id;

-- Calculate final order amount after discounts
SET @final_order_total = @order_total - (
  SELECT COALESCE(SUM(calculated_discount), 0) 
  FROM applicable_promotions
);

-- Transaction Operation 3: Reserve inventory with FIFO allocation
WITH inventory_allocation AS (
  SELECT 
    i._id as inventory_id,
    i.product_id,
    i.warehouse_location,
    i.available_quantity,
    i.unit_cost,
    oi.requested_quantity,

    -- Calculate allocation using FIFO
    ROW_NUMBER() OVER (
      PARTITION BY i.product_id 
      ORDER BY i.created_at ASC
    ) as allocation_order,

    -- Running total for allocation
    SUM(i.available_quantity) OVER (
      PARTITION BY i.product_id 
      ORDER BY i.created_at ASC 
      ROWS UNBOUNDED PRECEDING
    ) as cumulative_available

  FROM inventory i
  JOIN UNNEST(@order_items) AS oi ON i.product_id = oi.product_id
  WHERE i.available_quantity > 0 
    AND i.status = 'active'
),

allocation_plan AS (
  SELECT 
    inventory_id,
    product_id,
    warehouse_location,
    requested_quantity,

    -- Calculate exact quantity to allocate from each inventory record
    CASE 
      WHEN cumulative_available - available_quantity >= requested_quantity THEN 0
      WHEN cumulative_available >= requested_quantity THEN 
        requested_quantity - (cumulative_available - available_quantity)
      ELSE available_quantity
    END as quantity_to_allocate,

    unit_cost

  FROM inventory_allocation
  WHERE cumulative_available > 
    LAG(cumulative_available, 1, 0) OVER (PARTITION BY product_id ORDER BY allocation_order)
)

-- Execute inventory reservations
UPDATE inventory 
SET 
  available_quantity = available_quantity - ap.quantity_to_allocate,
  reserved_quantity = reserved_quantity + ap.quantity_to_allocate,
  reservations = ARRAY_APPEND(
    reservations,
    DOCUMENT(
      'reservation_id', CONCAT(@transaction_id, '_', ap.product_id, '_', ap.inventory_id),
      'order_id', @transaction_id,
      'quantity', ap.quantity_to_allocate,
      'reserved_at', CURRENT_TIMESTAMP,
      'expires_at', CURRENT_TIMESTAMP + INTERVAL '30 minutes',
      'status', 'active'
    )
  )
FROM allocation_plan ap
WHERE inventory._id = ap.inventory_id
  AND inventory.available_quantity >= ap.quantity_to_allocate;

-- Verify all inventory was successfully reserved
IF (
  SELECT SUM(quantity_to_allocate) FROM allocation_plan
) != (
  SELECT SUM(requested_quantity) FROM UNNEST(@order_items)
) THEN
  ROLLBACK TRANSACTION;
  THROW 'INSUFFICIENT_INVENTORY', 'Unable to reserve sufficient inventory for all items';
END IF;

-- Transaction Operation 4: Process payment with fraud detection
WITH fraud_assessment AS (
  SELECT 
    @user_id as user_id,
    @final_order_total as order_amount,

    -- Calculate fraud score based on multiple factors
    CASE
      -- Velocity check: orders in last 24 hours
      WHEN (
        SELECT COUNT(*) 
        FROM orders 
        WHERE customer.user_id = @user_id 
          AND lifecycle.created_at >= CURRENT_TIMESTAMP - INTERVAL '24 hours'
      ) > 5 THEN 0.3
      ELSE 0.0
    END +

    -- Amount anomaly check
    CASE
      WHEN @final_order_total > (
        SELECT AVG(pricing.final_amount) * 3 
        FROM orders 
        WHERE customer.user_id = @user_id
      ) THEN 0.2
      ELSE 0.0
    END +

    -- Time pattern check (unusual hours)
    CASE
      WHEN EXTRACT(HOUR FROM CURRENT_TIMESTAMP) BETWEEN 2 AND 6 THEN 0.1
      ELSE 0.0
    END +

    -- Geographic risk check
    CASE
      WHEN @ip_country != (SELECT country FROM users WHERE _id = @user_id) THEN 0.15
      ELSE 0.0
    END as fraud_score
)

-- Insert payment record with fraud assessment
INSERT INTO payments (
  _id,
  order_id,
  user_id,
  amount,
  original_amount,
  payment_method,
  authorization_id,
  capture_id,
  fraud_score,
  risk_assessment,
  status,
  processed_at
)
SELECT 
  CONCAT('payment_', @transaction_id),
  @transaction_id,
  @user_id,
  @final_order_total,
  @order_total,
  @payment_method,
  CONCAT('auth_', GENERATE_UUID()),
  CONCAT('capture_', GENERATE_UUID()),
  fa.fraud_score,
  DOCUMENT(
    'score', fa.fraud_score,
    'factors', ARRAY[
      'velocity_check',
      'amount_anomaly', 
      'time_pattern',
      'geographic_risk'
    ],
    'recommendation', 
    CASE WHEN fa.fraud_score > 0.5 THEN 'review' ELSE 'approve' END
  ),
  'completed',
  CURRENT_TIMESTAMP
FROM fraud_assessment fa
WHERE fa.fraud_score <= 0.8; -- Reject transactions with high fraud scores

-- Verify payment was processed (not rejected for fraud)
IF @@ROWCOUNT = 0 THEN
  ROLLBACK TRANSACTION;
  THROW 'FRAUD_DETECTED', 'Transaction flagged for potential fraud and rejected';
END IF;

-- Transaction Operation 5: Create comprehensive order document
INSERT INTO orders (
  _id,
  order_number,

  -- Customer information
  customer,

  -- Order items with inventory allocation
  items,

  -- Pricing breakdown  
  pricing,

  -- Payment information
  payment,

  -- Inventory allocation details
  inventory,

  -- Order lifecycle tracking
  status,
  lifecycle,

  -- Shipping information
  shipping,

  -- Transaction metadata
  transaction
)
VALUES (
  @transaction_id,
  CONCAT('ORD-', UNIX_TIMESTAMP(), '-', UPPER(RANDOM_STRING(6))),

  -- Customer document
  DOCUMENT(
    'user_id', @user_id,
    'email', (SELECT email FROM users WHERE _id = @user_id),
    'tier', (SELECT tier FROM users WHERE _id = @user_id),
    'is_returning_customer', (SELECT order_count > 0 FROM users WHERE _id = @user_id)
  ),

  -- Items with allocation details
  (
    SELECT ARRAY_AGG(
      DOCUMENT(
        'product_id', oi.product_id,
        'quantity', oi.quantity,
        'price', oi.price,
        'allocation', (
          SELECT ARRAY_AGG(
            DOCUMENT(
              'inventory_id', ap.inventory_id,
              'warehouse_location', ap.warehouse_location,
              'quantity', ap.quantity_to_allocate,
              'unit_cost', ap.unit_cost
            )
          )
          FROM allocation_plan ap
          WHERE ap.product_id = oi.product_id
        )
      )
    )
    FROM UNNEST(@order_items) AS oi
  ),

  -- Pricing breakdown document
  DOCUMENT(
    'subtotal', @order_total,
    'discounts', (
      SELECT ARRAY_AGG(
        DOCUMENT(
          'promotion_id', promotion_id,
          'promotion_name', promotion_name,
          'discount_amount', calculated_discount,
          'applied_at', CURRENT_TIMESTAMP
        )
      )
      FROM applicable_promotions
    ),
    'total_discount', @order_total - @final_order_total,
    'final_amount', @final_order_total,
    'tax', @tax_amount,
    'shipping', @shipping_cost,
    'total', @final_order_total + @tax_amount + @shipping_cost
  ),

  -- Payment document
  DOCUMENT(
    'payment_id', CONCAT('payment_', @transaction_id),
    'method', @payment_method,
    'status', 'completed',
    'fraud_score', (SELECT fraud_score FROM fraud_assessment),
    'processed_at', CURRENT_TIMESTAMP
  ),

  -- Inventory allocation document
  DOCUMENT(
    'reservation_id', @transaction_id,
    'total_items_reserved', (SELECT SUM(quantity_to_allocate) FROM allocation_plan),
    'reservation_details', (
      SELECT ARRAY_AGG(
        DOCUMENT(
          'product_id', product_id,
          'requested_quantity', requested_quantity,
          'allocated_from', ARRAY_AGG(
            DOCUMENT(
              'inventory_id', inventory_id,
              'warehouse_location', warehouse_location,
              'quantity', quantity_to_allocate,
              'unit_cost', unit_cost
            )
          )
        )
      )
      FROM allocation_plan
      GROUP BY product_id, requested_quantity
    )
  ),

  -- Order status and lifecycle
  'confirmed',
  DOCUMENT(
    'created_at', CURRENT_TIMESTAMP,
    'confirmed_at', CURRENT_TIMESTAMP,
    'estimated_fulfillment_date', CURRENT_TIMESTAMP + INTERVAL '2 days',
    'estimated_delivery_date', CURRENT_TIMESTAMP + INTERVAL '7 days'
  ),

  -- Shipping information
  DOCUMENT(
    'address', @shipping_address,
    'method', COALESCE(@shipping_method, 'standard'),
    'carrier', COALESCE(@carrier, 'fedex'),
    'tracking_number', NULL
  ),

  -- Transaction metadata
  DOCUMENT(
    'transaction_id', @transaction_id,
    'source', COALESCE(@order_source, 'web'),
    'channel', COALESCE(@order_channel, 'direct'),
    'user_agent', @user_agent,
    'ip_address', @ip_address
  )
);

-- Transaction Operation 6: Update loyalty points and tier status
WITH loyalty_calculation AS (
  SELECT 
    @user_id as user_id,
    FLOOR(@final_order_total) as base_points, -- 1 point per dollar

    -- Calculate bonus points based on items and categories
    (
      SELECT COALESCE(SUM(
        CASE 
          WHEN oi.category = 'electronics' THEN oi.quantity * 2
          WHEN oi.category = 'premium' THEN oi.quantity * 3
          ELSE 0
        END
      ), 0)
      FROM UNNEST(@order_items) AS oi
    ) +

    -- Order size bonus
    CASE 
      WHEN @final_order_total > 500 THEN 50
      WHEN @final_order_total > 200 THEN 20
      ELSE 0
    END as bonus_points
),

tier_calculation AS (
  SELECT 
    lc.user_id,
    lc.base_points + lc.bonus_points as total_points_earned,

    -- Calculate new tier based on lifetime value and points
    CASE
      WHEN (
        SELECT lifetime_value + @final_order_total FROM loyalty WHERE user_id = @user_id
      ) > 10000 AND (
        SELECT total_points_earned + (lc.base_points + lc.bonus_points) FROM loyalty WHERE user_id = @user_id
      ) > 5000 THEN 'platinum'

      WHEN (
        SELECT lifetime_value + @final_order_total FROM loyalty WHERE user_id = @user_id
      ) > 5000 AND (
        SELECT total_points_earned + (lc.base_points + lc.bonus_points) FROM loyalty WHERE user_id = @user_id
      ) > 2500 THEN 'gold'

      WHEN (
        SELECT lifetime_value + @final_order_total FROM loyalty WHERE user_id = @user_id
      ) > 1000 AND (
        SELECT total_points_earned + (lc.base_points + lc.bonus_points) FROM loyalty WHERE user_id = @user_id
      ) > 500 THEN 'silver'

      ELSE 'bronze'
    END as new_tier

  FROM loyalty_calculation lc
)

-- Update loyalty points
INSERT INTO loyalty (
  user_id,
  total_points_earned,
  available_points,
  lifetime_value,
  current_tier,
  points_history,
  last_activity_at
)
SELECT 
  tc.user_id,
  tc.total_points_earned,
  tc.total_points_earned,
  @final_order_total,
  tc.new_tier,
  ARRAY[
    DOCUMENT(
      'order_id', @transaction_id,
      'points_earned', tc.total_points_earned,
      'reason', 'order_purchase',
      'earned_at', CURRENT_TIMESTAMP
    )
  ],
  CURRENT_TIMESTAMP
FROM tier_calculation tc
ON DUPLICATE KEY UPDATE
  total_points_earned = total_points_earned + tc.total_points_earned,
  available_points = available_points + tc.total_points_earned,
  lifetime_value = lifetime_value + @final_order_total,
  current_tier = tc.new_tier,
  points_history = ARRAY_APPEND(
    points_history,
    DOCUMENT(
      'order_id', @transaction_id,
      'points_earned', tc.total_points_earned,
      'reason', 'order_purchase',
      'earned_at', CURRENT_TIMESTAMP
    )
  ),
  last_activity_at = CURRENT_TIMESTAMP;

-- Update user tier if changed
UPDATE users 
SET 
  tier = tc.new_tier,
  tier_history = ARRAY_APPEND(
    tier_history,
    DOCUMENT(
      'previous_tier', (SELECT current_tier FROM loyalty WHERE user_id = @user_id),
      'new_tier', tc.new_tier,
      'upgraded_at', CURRENT_TIMESTAMP,
      'triggered_by', @transaction_id
    )
  )
FROM tier_calculation tc
WHERE users._id = @user_id 
  AND users.tier != tc.new_tier;

-- Transaction Operation 7: Create comprehensive audit trail
INSERT INTO audit (
  _id,
  transaction_id,
  audit_type,

  -- Transaction context
  context,

  -- Detailed operation log  
  operations,

  -- Financial audit trail
  financial,

  -- Inventory audit trail
  inventory_audit,

  -- Compliance data
  compliance,

  -- Performance metrics
  performance,

  -- Audit metadata
  audited_at,
  retention_date,
  status
)
VALUES (
  CONCAT('audit_', @transaction_id),
  @transaction_id,
  'order_processing',

  -- Context document
  DOCUMENT(
    'user_id', @user_id,
    'user_email', (SELECT email FROM users WHERE _id = @user_id),
    'user_tier', (SELECT tier FROM users WHERE _id = @user_id),
    'source', @order_source,
    'user_agent', @user_agent,
    'ip_address', @ip_address
  ),

  -- Operations log
  ARRAY[
    DOCUMENT('collection', 'users', 'operation', 'validateAndUpdateUserAccount', 'timestamp', CURRENT_TIMESTAMP),
    DOCUMENT('collection', 'promotions', 'operation', 'applyPromotionsAndDiscounts', 'timestamp', CURRENT_TIMESTAMP),
    DOCUMENT('collection', 'inventory', 'operation', 'reserveInventoryWithAllocation', 'timestamp', CURRENT_TIMESTAMP),
    DOCUMENT('collection', 'payments', 'operation', 'processPaymentWithFraudDetection', 'timestamp', CURRENT_TIMESTAMP),
    DOCUMENT('collection', 'orders', 'operation', 'createComprehensiveOrder', 'timestamp', CURRENT_TIMESTAMP),
    DOCUMENT('collection', 'loyalty', 'operation', 'updateUserLoyaltyAndTier', 'timestamp', CURRENT_TIMESTAMP)
  ],

  -- Financial audit
  DOCUMENT(
    'original_amount', @order_total,
    'final_amount', @final_order_total,
    'discounts_applied', (SELECT COALESCE(COUNT(*), 0) FROM applicable_promotions),
    'total_discount', @order_total - @final_order_total,
    'payment_method', @payment_method,
    'fraud_score', (SELECT fraud_score FROM fraud_assessment)
  ),

  -- Inventory audit
  DOCUMENT(
    'reservation_id', @transaction_id,
    'items_reserved', (SELECT SUM(quantity_to_allocate) FROM allocation_plan),
    'allocation_details', (
      SELECT ARRAY_AGG(
        DOCUMENT(
          'product_id', product_id,
          'quantity_allocated', SUM(quantity_to_allocate),
          'warehouse_locations', ARRAY_AGG(DISTINCT warehouse_location)
        )
      )
      FROM allocation_plan
      GROUP BY product_id
    )
  ),

  -- Compliance information
  DOCUMENT(
    'data_processing_consent', COALESCE(@data_processing_consent, false),
    'marketing_consent', COALESCE(@marketing_consent, false),
    'privacy_policy_version', COALESCE(@privacy_policy_version, '1.0'),
    'terms_of_service_version', COALESCE(@terms_of_service_version, '1.0')
  ),

  -- Performance tracking
  DOCUMENT(
    'operations_executed', 7,
    'collections_affected', 6,
    'documents_modified', @@TOTAL_DOCUMENTS_MODIFIED
  ),

  -- Audit metadata
  CURRENT_TIMESTAMP,
  CURRENT_TIMESTAMP + INTERVAL '7 years', -- Retention period
  'completed'
);

-- Commit the entire transaction atomically
COMMIT TRANSACTION order_processing;

-- Advanced transaction monitoring and analysis queries
WITH transaction_performance_analysis AS (
  SELECT 
    DATE_TRUNC('hour', audited_at) as hour_bucket,
    audit_type as transaction_type,

    -- Performance metrics
    COUNT(*) as transaction_count,
    AVG(CAST(performance->>'operations_executed' AS INTEGER)) as avg_operations,
    AVG(CAST(performance->>'collections_affected' AS INTEGER)) as avg_collections,
    AVG(CAST(performance->>'documents_modified' AS INTEGER)) as avg_documents_modified,

    -- Financial metrics
    AVG(CAST(financial->>'final_amount' AS DECIMAL)) as avg_transaction_amount,
    SUM(CAST(financial->>'final_amount' AS DECIMAL)) as total_transaction_volume,
    AVG(CAST(financial->>'fraud_score' AS DECIMAL)) as avg_fraud_score,

    -- Success rate calculation
    COUNT(*) FILTER (WHERE status = 'completed') as successful_transactions,
    COUNT(*) FILTER (WHERE status != 'completed') as failed_transactions,
    ROUND(
      COUNT(*) FILTER (WHERE status = 'completed') * 100.0 / COUNT(*), 2
    ) as success_rate_pct

  FROM audit
  WHERE audited_at >= CURRENT_TIMESTAMP - INTERVAL '24 hours'
  GROUP BY DATE_TRUNC('hour', audited_at), audit_type
),

fraud_analysis AS (
  SELECT 
    DATE_TRUNC('day', audited_at) as day_bucket,

    -- Fraud detection metrics
    COUNT(*) as total_transactions,
    COUNT(*) FILTER (WHERE CAST(financial->>'fraud_score' AS DECIMAL) > 0.5) as high_risk_transactions,
    COUNT(*) FILTER (WHERE CAST(financial->>'fraud_score' AS DECIMAL) > 0.8) as rejected_transactions,
    AVG(CAST(financial->>'fraud_score' AS DECIMAL)) as avg_fraud_score,
    MAX(CAST(financial->>'fraud_score' AS DECIMAL)) as max_fraud_score,

    -- Risk distribution
    COUNT(*) FILTER (WHERE CAST(financial->>'fraud_score' AS DECIMAL) BETWEEN 0 AND 0.2) as low_risk,
    COUNT(*) FILTER (WHERE CAST(financial->>'fraud_score' AS DECIMAL) BETWEEN 0.2 AND 0.5) as medium_risk,
    COUNT(*) FILTER (WHERE CAST(financial->>'fraud_score' AS DECIMAL) BETWEEN 0.5 AND 0.8) as high_risk,
    COUNT(*) FILTER (WHERE CAST(financial->>'fraud_score' AS DECIMAL) > 0.8) as critical_risk

  FROM audit
  WHERE audited_at >= CURRENT_TIMESTAMP - INTERVAL '30 days'
    AND audit_type = 'order_processing'
  GROUP BY DATE_TRUNC('day', audited_at)
),

inventory_impact_analysis AS (
  SELECT 
    JSON_EXTRACT(inv_detail.value, '$.product_id') as product_id,

    -- Inventory allocation metrics
    SUM(CAST(JSON_EXTRACT(inv_detail.value, '$.quantity_allocated') AS INTEGER)) as total_allocated,
    COUNT(DISTINCT transaction_id) as allocation_transactions,
    AVG(CAST(JSON_EXTRACT(inv_detail.value, '$.quantity_allocated') AS INTEGER)) as avg_allocation_per_transaction,

    -- Warehouse distribution
    COUNT(DISTINCT JSON_EXTRACT(loc.value, '$')) as warehouses_used,
    JSON_ARRAYAGG(DISTINCT JSON_EXTRACT(loc.value, '$')) as warehouse_list

  FROM audit,
    JSON_TABLE(
      inventory_audit->'$.allocation_details', '$[*]'
      COLUMNS (
        value JSON PATH '$'
      )
    ) as inv_detail,
    JSON_TABLE(
      JSON_EXTRACT(inv_detail.value, '$.warehouse_locations'), '$[*]'
      COLUMNS (
        value JSON PATH '$'
      )
    ) as loc
  WHERE audited_at >= CURRENT_TIMESTAMP - INTERVAL '7 days'
    AND audit_type = 'order_processing'
  GROUP BY JSON_EXTRACT(inv_detail.value, '$.product_id')
  ORDER BY total_allocated DESC
  LIMIT 20
)

-- Comprehensive transaction monitoring dashboard
SELECT 
  'PERFORMANCE_SUMMARY' as metric_type,
  tpa.hour_bucket,
  tpa.transaction_type,
  tpa.transaction_count,
  tpa.avg_operations,
  tpa.avg_transaction_amount,
  tpa.success_rate_pct,

  -- Performance grading
  CASE 
    WHEN tpa.success_rate_pct >= 99.5 AND tpa.avg_operations <= 10 THEN 'EXCELLENT'
    WHEN tpa.success_rate_pct >= 99.0 AND tpa.avg_operations <= 15 THEN 'GOOD'
    WHEN tpa.success_rate_pct >= 95.0 THEN 'ACCEPTABLE'
    ELSE 'NEEDS_IMPROVEMENT'
  END as performance_grade

FROM transaction_performance_analysis tpa

UNION ALL

SELECT 
  'FRAUD_SUMMARY' as metric_type,
  fa.day_bucket::timestamp,
  'fraud_analysis',
  fa.total_transactions,
  fa.avg_fraud_score,
  fa.max_fraud_score,
  ROUND(fa.rejected_transactions * 100.0 / fa.total_transactions, 2) as rejection_rate_pct,

  -- Risk level assessment
  CASE
    WHEN fa.avg_fraud_score < 0.2 THEN 'LOW_RISK'
    WHEN fa.avg_fraud_score < 0.5 THEN 'MEDIUM_RISK'  
    WHEN fa.avg_fraud_score < 0.8 THEN 'HIGH_RISK'
    ELSE 'CRITICAL_RISK'
  END as risk_level

FROM fraud_analysis fa

UNION ALL

SELECT 
  'INVENTORY_SUMMARY' as metric_type,
  CURRENT_TIMESTAMP,
  'inventory_allocation',
  iia.allocation_transactions,
  iia.total_allocated,
  iia.avg_allocation_per_transaction,
  iia.warehouses_used,

  -- Allocation efficiency
  CASE
    WHEN iia.warehouses_used = 1 THEN 'SINGLE_WAREHOUSE'
    WHEN iia.warehouses_used <= 3 THEN 'EFFICIENT_DISTRIBUTION'
    ELSE 'FRAGMENTED_ALLOCATION'
  END as allocation_pattern

FROM inventory_impact_analysis iia
ORDER BY metric_type, hour_bucket DESC;

-- Real-time transaction health monitoring
CREATE MATERIALIZED VIEW transaction_health_dashboard AS
WITH real_time_metrics AS (
  SELECT 
    DATE_TRUNC('minute', audited_at) as minute_bucket,
    audit_type,

    -- Real-time performance metrics
    COUNT(*) as transactions_per_minute,
    AVG(CAST(performance->>'operations_executed' AS INTEGER)) as avg_operations,
    COUNT(*) FILTER (WHERE status = 'completed') as successful_transactions,
    COUNT(*) FILTER (WHERE status != 'completed') as failed_transactions,

    -- Financial metrics
    SUM(CAST(financial->>'final_amount' AS DECIMAL)) as revenue_per_minute,
    AVG(CAST(financial->>'fraud_score' AS DECIMAL)) as avg_fraud_score,

    -- Operational metrics
    AVG(CAST(performance->>'documents_modified' AS INTEGER)) as avg_documents_per_transaction

  FROM audit
  WHERE audited_at >= CURRENT_TIMESTAMP - INTERVAL '1 hour'
  GROUP BY DATE_TRUNC('minute', audited_at), audit_type
),

health_indicators AS (
  SELECT 
    minute_bucket,
    audit_type,
    transactions_per_minute,
    successful_transactions,
    failed_transactions,
    revenue_per_minute,
    avg_fraud_score,

    -- Calculate success rate
    CASE WHEN transactions_per_minute > 0 THEN
      ROUND(successful_transactions * 100.0 / transactions_per_minute, 2)
    ELSE 0 END as success_rate,

    -- Detect anomalies
    CASE 
      WHEN failed_transactions > successful_transactions THEN 'CRITICAL_FAILURE_RATE'
      WHEN successful_transactions = 0 AND transactions_per_minute > 0 THEN 'COMPLETE_FAILURE'
      WHEN avg_fraud_score > 0.6 THEN 'HIGH_FRAUD_ACTIVITY' 
      WHEN transactions_per_minute > 100 THEN 'HIGH_VOLUME_ALERT'
      WHEN transactions_per_minute = 0 AND EXTRACT(HOUR FROM CURRENT_TIMESTAMP) BETWEEN 9 AND 21 THEN 'NO_TRANSACTIONS_ALERT'
      ELSE 'NORMAL'
    END as health_status,

    -- Performance trend
    LAG(successful_transactions) OVER (
      PARTITION BY audit_type 
      ORDER BY minute_bucket
    ) as prev_minute_success,

    LAG(failed_transactions) OVER (
      PARTITION BY audit_type 
      ORDER BY minute_bucket  
    ) as prev_minute_failures

  FROM real_time_metrics
)

SELECT 
  minute_bucket,
  audit_type,
  transactions_per_minute,
  success_rate,
  revenue_per_minute,
  health_status,
  avg_fraud_score,

  -- Trend analysis
  CASE 
    WHEN prev_minute_success IS NOT NULL THEN
      successful_transactions - prev_minute_success
    ELSE 0
  END as success_trend,

  CASE 
    WHEN prev_minute_failures IS NOT NULL THEN  
      failed_transactions - prev_minute_failures
    ELSE 0
  END as failure_trend,

  -- Alert priority
  CASE health_status
    WHEN 'COMPLETE_FAILURE' THEN 1
    WHEN 'CRITICAL_FAILURE_RATE' THEN 2
    WHEN 'HIGH_FRAUD_ACTIVITY' THEN 3
    WHEN 'HIGH_VOLUME_ALERT' THEN 4
    WHEN 'NO_TRANSACTIONS_ALERT' THEN 5
    ELSE 10
  END as alert_priority,

  -- Recommendations
  CASE health_status
    WHEN 'COMPLETE_FAILURE' THEN 'IMMEDIATE: Check system connectivity and database status'
    WHEN 'CRITICAL_FAILURE_RATE' THEN 'HIGH: Review error logs and investigate transaction failures'
    WHEN 'HIGH_FRAUD_ACTIVITY' THEN 'MEDIUM: Review fraud detection rules and recent transactions'
    WHEN 'HIGH_VOLUME_ALERT' THEN 'LOW: Monitor system resources and scaling capabilities'
    WHEN 'NO_TRANSACTIONS_ALERT' THEN 'MEDIUM: Check application availability and user access'
    ELSE 'Continue monitoring'
  END as recommendation

FROM health_indicators
WHERE minute_bucket >= CURRENT_TIMESTAMP - INTERVAL '15 minutes'
ORDER BY alert_priority ASC, minute_bucket DESC;

-- QueryLeaf provides comprehensive transaction management:
-- 1. SQL-familiar syntax for complex MongoDB multi-document transactions
-- 2. Full ACID compliance with automatic rollback on failure
-- 3. Advanced business logic integration within transactional contexts
-- 4. Comprehensive audit trail generation with regulatory compliance
-- 5. Real-time fraud detection and risk assessment within transactions
-- 6. Sophisticated inventory allocation and reservation management
-- 7. Dynamic promotions and loyalty points calculation in transactions
-- 8. Performance monitoring and alerting for transaction health
-- 9. Automated retry logic and error handling for transient failures
-- 10. Production-ready transaction patterns with comprehensive monitoring

Best Practices for MongoDB Transaction Implementation

Transaction Design Principles

Essential guidelines for effective MongoDB transaction usage:

  1. Minimize Transaction Scope: Keep transactions as short as possible to reduce lock contention and improve performance
  2. Idempotent Operations: Design transaction operations to be safely retryable in case of transient failures
  3. Proper Error Handling: Implement comprehensive error handling with appropriate retry logic for transient errors
  4. Read and Write Concerns: Configure appropriate read and write concerns for consistency requirements
  5. Timeout Management: Set reasonable timeouts to prevent long-running transactions from blocking resources
  6. Performance Monitoring: Monitor transaction performance and identify bottlenecks or long-running operations

Production Optimization Strategies

Optimize MongoDB transactions for production environments:

  1. Connection Pooling: Use connection pooling to efficiently manage database connections across transaction sessions
  2. Index Optimization: Ensure proper indexing for all queries within transactions to minimize lock duration
  3. Batch Operations: Use bulk operations where possible to reduce the number of round trips and improve performance
  4. Monitoring and Alerting: Implement comprehensive monitoring for transaction success rates, latency, and error patterns
  5. Capacity Planning: Plan for transaction concurrency and ensure sufficient resources for peak transaction loads
  6. Testing and Validation: Regularly test transaction logic under load to identify potential issues before production

Conclusion

MongoDB's multi-document ACID transactions provide comprehensive atomic operations that eliminate the complexity and consistency challenges of traditional NoSQL coordination approaches. The sophisticated transaction management, automatic retry logic, and comprehensive error handling ensure reliable business operations while maintaining the flexibility and scalability benefits of MongoDB's document model.

Key MongoDB Transaction benefits include:

  • Full ACID Compliance: Complete atomicity, consistency, isolation, and durability guarantees across multiple documents
  • Automatic Rollback: Built-in rollback functionality eliminates complex application-level coordination requirements
  • Cross-Collection Atomicity: Multi-document operations spanning different collections within the same database
  • Retry Logic: Intelligent retry mechanisms for transient errors and network issues
  • Performance Optimization: Advanced transaction management with connection pooling and batch operations
  • Comprehensive Monitoring: Built-in transaction metrics and monitoring capabilities for production environments

Whether you're building financial applications, e-commerce platforms, or complex workflow systems, MongoDB's ACID transactions with QueryLeaf's familiar SQL interface provide the foundation for reliable, consistent, and scalable multi-document operations.

QueryLeaf Integration: QueryLeaf automatically manages MongoDB transaction operations while providing SQL-familiar syntax for complex multi-document business logic, comprehensive error handling, and advanced transaction patterns. ACID compliance, automatic retry logic, and production monitoring capabilities are seamlessly handled through familiar SQL constructs, making sophisticated transactional applications both powerful and accessible to SQL-oriented development teams.

The combination of MongoDB's robust transaction capabilities with SQL-style operations makes it an ideal platform for applications requiring both NoSQL flexibility and traditional database transaction guarantees, ensuring your business operations maintain consistency and reliability as they scale and evolve.

MongoDB Change Streams and Real-time Event Processing: Advanced Microservices Architecture Patterns for Event-Driven Applications

Modern distributed applications require sophisticated event-driven architectures that can process real-time data changes, coordinate microservices communication, and maintain system consistency across complex distributed topologies. Traditional polling-based approaches to change detection introduce latency, resource waste, and scaling challenges that become increasingly problematic as application complexity and data volumes grow.

MongoDB Change Streams provide a powerful, efficient mechanism for building reactive applications that respond to data changes in real-time without the overhead and complexity of traditional change detection patterns. Unlike database triggers or polling-based solutions that require complex infrastructure and introduce performance bottlenecks, Change Streams offer a scalable, resumable, and ordered stream of change events that enables sophisticated event-driven architectures, microservices coordination, and real-time analytics.

The Traditional Change Detection Challenge

Conventional change detection approaches suffer from significant limitations for real-time application requirements:

-- Traditional PostgreSQL change detection with LISTEN/NOTIFY - limited scalability and functionality

-- Basic trigger-based notification system
CREATE OR REPLACE FUNCTION notify_order_changes()
RETURNS TRIGGER AS $$
BEGIN
  IF TG_OP = 'INSERT' THEN
    PERFORM pg_notify('order_created', json_build_object(
      'operation', 'INSERT',
      'order_id', NEW.order_id,
      'user_id', NEW.user_id,
      'total_amount', NEW.total_amount,
      'timestamp', NOW()
    )::text);
    RETURN NEW;
  ELSIF TG_OP = 'UPDATE' THEN
    PERFORM pg_notify('order_updated', json_build_object(
      'operation', 'UPDATE',
      'order_id', NEW.order_id,
      'old_status', OLD.status,
      'new_status', NEW.status,
      'timestamp', NOW()
    )::text);
    RETURN NEW;
  ELSIF TG_OP = 'DELETE' THEN
    PERFORM pg_notify('order_deleted', json_build_object(
      'operation', 'DELETE',
      'order_id', OLD.order_id,
      'user_id', OLD.user_id,
      'timestamp', NOW()
    )::text);
    RETURN OLD;
  END IF;
  RETURN NULL;
END;
$$ LANGUAGE plpgsql;

-- Attach triggers to orders table
CREATE TRIGGER order_changes_trigger
  AFTER INSERT OR UPDATE OR DELETE ON orders
  FOR EACH ROW EXECUTE FUNCTION notify_order_changes();

-- Client-side change listening with significant limitations
-- Node.js example showing polling approach complexity

const { Client } = require('pg');
const EventEmitter = require('events');

class PostgreSQLChangeListener extends EventEmitter {
  constructor(connectionConfig) {
    super();
    this.client = new Client(connectionConfig);
    this.isListening = false;
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 5;
    this.lastProcessedId = null;

    // Complex connection management required
    this.setupErrorHandlers();
  }

  async startListening() {
    try {
      await this.client.connect();

      // Listen to specific channels
      await this.client.query('LISTEN order_created');
      await this.client.query('LISTEN order_updated');
      await this.client.query('LISTEN order_deleted');
      await this.client.query('LISTEN user_activity');

      this.isListening = true;
      console.log('Started listening for database changes...');

      // Handle incoming notifications
      this.client.on('notification', async (msg) => {
        try {
          const changeData = JSON.parse(msg.payload);
          await this.processChange(msg.channel, changeData);
        } catch (error) {
          console.error('Error processing notification:', error);
          this.emit('error', error);
        }
      });

      // Poll for missed changes during disconnection
      this.startMissedChangePolling();

    } catch (error) {
      console.error('Failed to start listening:', error);
      await this.handleReconnection();
    }
  }

  async processChange(channel, changeData) {
    console.log(`Processing ${channel} change:`, changeData);

    // Complex event processing logic
    switch (channel) {
      case 'order_created':
        await this.handleOrderCreated(changeData);
        break;
      case 'order_updated':
        await this.handleOrderUpdated(changeData);
        break;
      case 'order_deleted':
        await this.handleOrderDeleted(changeData);
        break;
      default:
        console.warn(`Unknown channel: ${channel}`);
    }

    // Update processing checkpoint
    this.lastProcessedId = changeData.order_id;
  }

  async handleOrderCreated(orderData) {
    // Microservice coordination complexity
    const coordinationTasks = [
      this.notifyInventoryService(orderData),
      this.notifyPaymentService(orderData),
      this.notifyShippingService(orderData),
      this.notifyAnalyticsService(orderData),
      this.updateCustomerProfile(orderData)
    ];

    try {
      await Promise.all(coordinationTasks);
      console.log(`Successfully coordinated order creation: ${orderData.order_id}`);
    } catch (error) {
      console.error('Coordination failed:', error);
      // Complex error handling and retry logic required
      await this.handleCoordinationFailure(orderData, error);
    }
  }

  async startMissedChangePolling() {
    // Polling fallback for missed changes during disconnection
    setInterval(async () => {
      if (!this.isListening) return;

      try {
        const query = `
          SELECT 
            o.order_id,
            o.user_id,
            o.status,
            o.total_amount,
            o.created_at,
            o.updated_at,
            'order' as entity_type,
            CASE 
              WHEN o.created_at > NOW() - INTERVAL '5 minutes' THEN 'created'
              WHEN o.updated_at > NOW() - INTERVAL '5 minutes' THEN 'updated'
            END as change_type
          FROM orders o
          WHERE (o.created_at > NOW() - INTERVAL '5 minutes' 
                 OR o.updated_at > NOW() - INTERVAL '5 minutes')
            AND o.order_id > $1
          ORDER BY o.order_id
          LIMIT 1000
        `;

        const result = await this.client.query(query, [this.lastProcessedId || 0]);

        for (const row of result.rows) {
          await this.processChange(`order_${row.change_type}`, row);
        }

      } catch (error) {
        console.error('Polling error:', error);
      }
    }, 30000); // Poll every 30 seconds
  }

  async handleReconnection() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.error('Max reconnection attempts reached');
      this.emit('fatal_error', new Error('Connection permanently lost'));
      return;
    }

    this.reconnectAttempts++;
    const delay = Math.pow(2, this.reconnectAttempts) * 1000; // Exponential backoff

    console.log(`Attempting reconnection ${this.reconnectAttempts}/${this.maxReconnectAttempts} in ${delay}ms`);

    setTimeout(async () => {
      try {
        await this.client.end();
        this.client = new Client(this.connectionConfig);
        this.setupErrorHandlers();
        await this.startListening();
        this.reconnectAttempts = 0;
      } catch (error) {
        console.error('Reconnection failed:', error);
        await this.handleReconnection();
      }
    }, delay);
  }

  setupErrorHandlers() {
    this.client.on('error', async (error) => {
      console.error('PostgreSQL connection error:', error);
      this.isListening = false;
      await this.handleReconnection();
    });

    this.client.on('end', () => {
      console.log('PostgreSQL connection ended');
      this.isListening = false;
    });
  }
}

// Problems with traditional PostgreSQL LISTEN/NOTIFY approach:
// 1. Limited payload size (8000 bytes) restricts change data detail
// 2. No guaranteed delivery - notifications lost during disconnection
// 3. No ordering guarantees across multiple channels
// 4. Complex reconnection and missed change handling logic required
// 5. Limited filtering capabilities - all listeners receive all notifications
// 6. No built-in support for change resumption from specific points
// 7. Scalability limitations with many concurrent listeners
// 8. Manual coordination required for microservices communication
// 9. Complex error handling and retry mechanisms needed
// 10. No native support for document-level change tracking

// MySQL limitations are even more restrictive
-- MySQL basic replication events (limited functionality)
SHOW MASTER STATUS;
SHOW SLAVE STATUS;

-- MySQL binary log parsing (complex and fragile)
-- Requires external tools like Maxwell or Debezium
-- Limited change event structure and filtering
-- Complex setup and operational overhead
-- No native application-level change streams
-- Poor support for real-time event processing

MongoDB Change Streams provide comprehensive real-time change processing:

// MongoDB Change Streams - comprehensive real-time event processing with advanced patterns
const { MongoClient } = require('mongodb');
const EventEmitter = require('events');

const client = new MongoClient('mongodb://localhost:27017');
const db = client.db('ecommerce_platform');

// Advanced MongoDB Change Streams manager for microservices architecture
class MongoChangeStreamManager extends EventEmitter {
  constructor(db) {
    super();
    this.db = db;
    this.collections = {
      orders: db.collection('orders'),
      users: db.collection('users'),
      products: db.collection('products'),
      inventory: db.collection('inventory'),
      payments: db.collection('payments')
    };

    this.changeStreams = new Map();
    this.eventProcessors = new Map();
    this.resumeTokens = new Map();
    this.processingStats = new Map();

    // Advanced configuration for production use
    this.streamConfig = {
      batchSize: 100,
      maxAwaitTimeMS: 1000,
      fullDocument: 'updateLookup',
      fullDocumentBeforeChange: 'whenAvailable',
      startAtOperationTime: null,
      resumeAfter: null
    };

    // Event processing pipeline
    this.eventQueue = [];
    this.isProcessing = false;
    this.maxQueueSize = 10000;

    this.setupEventProcessors();
  }

  async initializeChangeStreams(streamConfigurations) {
    console.log('Initializing MongoDB Change Streams for microservices architecture...');

    for (const [streamName, config] of Object.entries(streamConfigurations)) {
      try {
        console.log(`Setting up change stream: ${streamName}`);
        await this.createChangeStream(streamName, config);
      } catch (error) {
        console.error(`Failed to create change stream ${streamName}:`, error);
        this.emit('stream_error', { streamName, error });
      }
    }

    // Start event processing
    this.startEventProcessing();

    console.log(`${this.changeStreams.size} change streams initialized successfully`);
    return this.getStreamStatus();
  }

  async createChangeStream(streamName, config) {
    const {
      collection,
      pipeline = [],
      options = {},
      processor,
      resumeToken = null
    } = config;

    // Build comprehensive change stream pipeline
    const changeStreamPipeline = [
      // Stage 1: Filter by operation types if specified
      ...(config.operationTypes ? [
        { $match: { operationType: { $in: config.operationTypes } } }
      ] : []),

      // Stage 2: Document-level filtering
      ...(config.documentFilter ? [
        { $match: config.documentFilter }
      ] : []),

      // Stage 3: Field-level filtering for efficiency
      ...(config.fieldFilter ? [
        { $project: config.fieldFilter }
      ] : []),

      // Custom pipeline stages
      ...pipeline
    ];

    const streamOptions = {
      ...this.streamConfig,
      ...options,
      ...(resumeToken && { resumeAfter: resumeToken })
    };

    const targetCollection = this.collections[collection] || this.db.collection(collection);
    const changeStream = targetCollection.watch(changeStreamPipeline, streamOptions);

    // Configure change stream event handlers
    this.setupChangeStreamHandlers(streamName, changeStream, processor);

    this.changeStreams.set(streamName, {
      stream: changeStream,
      collection: collection,
      processor: processor,
      config: config,
      stats: {
        eventsProcessed: 0,
        errors: 0,
        lastEventTime: null,
        startTime: new Date()
      }
    });

    console.log(`Change stream '${streamName}' created for collection '${collection}'`);
    return changeStream;
  }

  setupChangeStreamHandlers(streamName, changeStream, processor) {
    changeStream.on('change', async (changeDoc) => {
      try {
        // Extract resume token for fault tolerance
        this.resumeTokens.set(streamName, changeDoc._id);

        // Add comprehensive change metadata
        const enhancedChange = {
          ...changeDoc,
          streamName: streamName,
          receivedAt: new Date(),
          processingMetadata: {
            retryCount: 0,
            priority: this.calculateEventPriority(changeDoc),
            correlationId: this.generateCorrelationId(changeDoc),
            traceId: this.generateTraceId()
          }
        };

        // Queue for processing
        await this.queueChangeEvent(enhancedChange, processor);

        // Update statistics
        this.updateStreamStats(streamName, 'event_received');

      } catch (error) {
        console.error(`Error handling change in stream ${streamName}:`, error);
        this.updateStreamStats(streamName, 'error');
        this.emit('change_error', { streamName, error, changeDoc });
      }
    });

    changeStream.on('error', async (error) => {
      console.error(`Change stream ${streamName} error:`, error);
      this.updateStreamStats(streamName, 'stream_error');

      // Attempt to resume from last known position
      if (error.code === 40585 || error.code === 136) { // Resume token expired or invalid
        console.log(`Attempting to resume change stream ${streamName}...`);
        await this.resumeChangeStream(streamName);
      } else {
        this.emit('stream_error', { streamName, error });
      }
    });

    changeStream.on('close', () => {
      console.log(`Change stream ${streamName} closed`);
      this.emit('stream_closed', { streamName });
    });
  }

  async queueChangeEvent(changeEvent, processor) {
    // Prevent queue overflow
    if (this.eventQueue.length >= this.maxQueueSize) {
      console.warn('Event queue at capacity, dropping oldest events');
      this.eventQueue.splice(0, Math.floor(this.maxQueueSize * 0.1)); // Drop 10% of oldest
    }

    // Add event to processing queue with priority ordering
    this.eventQueue.push({ changeEvent, processor });
    this.eventQueue.sort((a, b) => 
      b.changeEvent.processingMetadata.priority - a.changeEvent.processingMetadata.priority
    );

    // Start processing if not already running
    if (!this.isProcessing) {
      setImmediate(() => this.processEventQueue());
    }
  }

  async processEventQueue() {
    if (this.isProcessing || this.eventQueue.length === 0) return;

    this.isProcessing = true;

    try {
      while (this.eventQueue.length > 0) {
        const { changeEvent, processor } = this.eventQueue.shift();

        try {
          const startTime = Date.now();
          await this.processChangeEvent(changeEvent, processor);
          const processingTime = Date.now() - startTime;

          // Update processing metrics
          this.updateProcessingMetrics(changeEvent.streamName, processingTime, true);

        } catch (error) {
          console.error('Event processing failed:', error);

          // Implement retry logic
          if (changeEvent.processingMetadata.retryCount < 3) {
            changeEvent.processingMetadata.retryCount++;
            changeEvent.processingMetadata.priority -= 1; // Lower priority for retries
            this.eventQueue.unshift({ changeEvent, processor });
          } else {
            console.error('Max retries reached for event:', changeEvent._id);
            this.emit('event_failed', { changeEvent, error });
          }

          this.updateProcessingMetrics(changeEvent.streamName, 0, false);
        }
      }
    } finally {
      this.isProcessing = false;
    }
  }

  async processChangeEvent(changeEvent, processor) {
    const { operationType, fullDocument, documentKey, updateDescription } = changeEvent;

    console.log(`Processing ${operationType} event for ${changeEvent.streamName}`);

    // Execute processor function with comprehensive context
    const processingContext = {
      operation: operationType,
      document: fullDocument,
      documentKey: documentKey,
      updateDescription: updateDescription,
      timestamp: changeEvent.clusterTime,
      metadata: changeEvent.processingMetadata,

      // Utility functions
      isInsert: () => operationType === 'insert',
      isUpdate: () => operationType === 'update',
      isDelete: () => operationType === 'delete',
      isReplace: () => operationType === 'replace',

      // Field change utilities
      hasFieldChanged: (fieldName) => {
        return updateDescription?.updatedFields?.hasOwnProperty(fieldName) ||
               updateDescription?.removedFields?.includes(fieldName);
      },

      getFieldChange: (fieldName) => {
        return updateDescription?.updatedFields?.[fieldName];
      },

      // Document utilities
      getDocumentId: () => documentKey._id,
      getFullDocument: () => fullDocument
    };

    // Execute the processor
    await processor(processingContext);
  }

  setupEventProcessors() {
    // Order lifecycle management processor
    this.eventProcessors.set('orderLifecycle', async (context) => {
      const { operation, document, hasFieldChanged } = context;

      switch (operation) {
        case 'insert':
          await this.handleOrderCreated(document);
          break;

        case 'update':
          if (hasFieldChanged('status')) {
            await this.handleOrderStatusChange(document, context.getFieldChange('status'));
          }
          if (hasFieldChanged('payment_status')) {
            await this.handlePaymentStatusChange(document, context.getFieldChange('payment_status'));
          }
          if (hasFieldChanged('shipping_status')) {
            await this.handleShippingStatusChange(document, context.getFieldChange('shipping_status'));
          }
          break;

        case 'delete':
          await this.handleOrderCancelled(context.getDocumentId());
          break;
      }
    });

    // Inventory management processor
    this.eventProcessors.set('inventorySync', async (context) => {
      const { operation, document, hasFieldChanged } = context;

      if (operation === 'insert' && document.items) {
        // New order - reserve inventory
        await this.reserveInventoryForOrder(document);
      } else if (operation === 'update' && hasFieldChanged('status')) {
        const newStatus = context.getFieldChange('status');

        if (newStatus === 'cancelled') {
          await this.releaseInventoryReservation(document);
        } else if (newStatus === 'shipped') {
          await this.confirmInventoryConsumption(document);
        }
      }
    });

    // Real-time analytics processor
    this.eventProcessors.set('realTimeAnalytics', async (context) => {
      const { operation, document, timestamp } = context;

      // Update real-time metrics
      const analyticsEvent = {
        eventType: `order_${operation}`,
        timestamp: timestamp,
        data: {
          orderId: context.getDocumentId(),
          customerId: document?.user_id,
          amount: document?.total_amount,
          region: document?.shipping_address?.region,
          products: document?.items?.map(item => item.product_id)
        }
      };

      await this.updateRealTimeMetrics(analyticsEvent);
    });

    // Customer engagement processor
    this.eventProcessors.set('customerEngagement', async (context) => {
      const { operation, document, hasFieldChanged } = context;

      if (operation === 'insert') {
        // New order - update customer profile
        await this.updateCustomerOrderHistory(document.user_id, document);

        // Trigger post-purchase engagement
        await this.triggerPostPurchaseEngagement(document);

      } else if (operation === 'update' && hasFieldChanged('status')) {
        const newStatus = context.getFieldChange('status');

        if (newStatus === 'delivered') {
          // Order delivered - trigger review request
          await this.triggerReviewRequest(document);
        }
      }
    });
  }

  async handleOrderCreated(orderDocument) {
    console.log(`Processing new order: ${orderDocument._id}`);

    // Coordinate microservices for order creation
    const coordinationTasks = [
      this.notifyPaymentService({
        action: 'process_payment',
        orderId: orderDocument._id,
        amount: orderDocument.total_amount,
        paymentMethod: orderDocument.payment_method
      }),

      this.notifyInventoryService({
        action: 'reserve_inventory',
        orderId: orderDocument._id,
        items: orderDocument.items
      }),

      this.notifyShippingService({
        action: 'calculate_shipping',
        orderId: orderDocument._id,
        shippingAddress: orderDocument.shipping_address,
        items: orderDocument.items
      }),

      this.notifyCustomerService({
        action: 'order_confirmation',
        orderId: orderDocument._id,
        customerId: orderDocument.user_id
      })
    ];

    // Execute coordination with error handling
    const results = await Promise.allSettled(coordinationTasks);

    // Check for coordination failures
    const failures = results.filter(result => result.status === 'rejected');
    if (failures.length > 0) {
      console.error(`Order coordination failures for ${orderDocument._id}:`, failures);

      // Trigger compensation workflow
      await this.triggerCompensationWorkflow(orderDocument._id, failures);
    }
  }

  async handleOrderStatusChange(orderDocument, newStatus) {
    console.log(`Order ${orderDocument._id} status changed to: ${newStatus}`);

    const statusHandlers = {
      'confirmed': async () => {
        await this.notifyFulfillmentService({
          action: 'prepare_order',
          orderId: orderDocument._id
        });
      },

      'shipped': async () => {
        await this.notifyCustomerService({
          action: 'shipping_notification',
          orderId: orderDocument._id,
          trackingNumber: orderDocument.tracking_number
        });

        // Update inventory
        await this.confirmInventoryConsumption(orderDocument);
      },

      'delivered': async () => {
        // Trigger post-delivery workflows
        await Promise.all([
          this.triggerReviewRequest(orderDocument),
          this.updateCustomerLoyaltyPoints(orderDocument),
          this.analyzeReorderProbability(orderDocument)
        ]);
      },

      'cancelled': async () => {
        // Execute cancellation compensation
        await this.executeOrderCancellation(orderDocument);
      }
    };

    const handler = statusHandlers[newStatus];
    if (handler) {
      await handler();
    }
  }

  async reserveInventoryForOrder(orderDocument) {
    console.log(`Reserving inventory for order: ${orderDocument._id}`);

    const inventoryOperations = orderDocument.items.map(item => ({
      updateOne: {
        filter: {
          product_id: item.product_id,
          available_quantity: { $gte: item.quantity }
        },
        update: {
          $inc: {
            available_quantity: -item.quantity,
            reserved_quantity: item.quantity
          },
          $push: {
            reservations: {
              order_id: orderDocument._id,
              quantity: item.quantity,
              reserved_at: new Date(),
              expires_at: new Date(Date.now() + 30 * 60 * 1000) // 30 minutes
            }
          }
        }
      }
    }));

    try {
      const result = await this.collections.inventory.bulkWrite(inventoryOperations);
      console.log(`Inventory reserved for ${result.modifiedCount} items`);

      // Check for insufficient inventory
      if (result.modifiedCount < orderDocument.items.length) {
        await this.handleInsufficientInventory(orderDocument, result);
      }

    } catch (error) {
      console.error(`Inventory reservation failed for order ${orderDocument._id}:`, error);
      throw error;
    }
  }

  async updateRealTimeMetrics(analyticsEvent) {
    console.log(`Updating real-time metrics for: ${analyticsEvent.eventType}`);

    const metricsUpdate = {
      $inc: {
        [`hourly_metrics.${new Date().getHours()}.${analyticsEvent.eventType}`]: 1
      },
      $push: {
        recent_events: {
          $each: [analyticsEvent],
          $slice: -1000 // Keep last 1000 events
        }
      },
      $set: {
        last_updated: new Date()
      }
    };

    // Update regional metrics
    if (analyticsEvent.data.region) {
      metricsUpdate.$inc[`regional_metrics.${analyticsEvent.data.region}.${analyticsEvent.eventType}`] = 1;
    }

    await this.collections.analytics.updateOne(
      { _id: 'real_time_metrics' },
      metricsUpdate,
      { upsert: true }
    );
  }

  async triggerPostPurchaseEngagement(orderDocument) {
    console.log(`Triggering post-purchase engagement for order: ${orderDocument._id}`);

    // Schedule engagement activities
    const engagementTasks = [
      {
        type: 'order_confirmation_email',
        scheduledFor: new Date(Date.now() + 5 * 60 * 1000), // 5 minutes
        recipient: orderDocument.user_id,
        data: { orderId: orderDocument._id }
      },
      {
        type: 'shipping_updates_subscription',
        scheduledFor: new Date(Date.now() + 60 * 60 * 1000), // 1 hour
        recipient: orderDocument.user_id,
        data: { orderId: orderDocument._id }
      },
      {
        type: 'product_recommendations',
        scheduledFor: new Date(Date.now() + 24 * 60 * 60 * 1000), // 24 hours
        recipient: orderDocument.user_id,
        data: { 
          orderId: orderDocument._id,
          purchasedProducts: orderDocument.items.map(item => item.product_id)
        }
      }
    ];

    await this.collections.engagement_queue.insertMany(engagementTasks);
  }

  // Microservice communication methods
  async notifyPaymentService(message) {
    // In production, this would use message queues (RabbitMQ, Apache Kafka, etc.)
    console.log('Notifying Payment Service:', message);

    // Simulate service call
    return new Promise((resolve) => {
      setTimeout(() => {
        console.log(`Payment service processed: ${message.action}`);
        resolve({ status: 'success', processedAt: new Date() });
      }, 100);
    });
  }

  async notifyInventoryService(message) {
    console.log('Notifying Inventory Service:', message);

    return new Promise((resolve) => {
      setTimeout(() => {
        console.log(`Inventory service processed: ${message.action}`);
        resolve({ status: 'success', processedAt: new Date() });
      }, 150);
    });
  }

  async notifyShippingService(message) {
    console.log('Notifying Shipping Service:', message);

    return new Promise((resolve) => {
      setTimeout(() => {
        console.log(`Shipping service processed: ${message.action}`);
        resolve({ status: 'success', processedAt: new Date() });
      }, 200);
    });
  }

  async notifyCustomerService(message) {
    console.log('Notifying Customer Service:', message);

    return new Promise((resolve) => {
      setTimeout(() => {
        console.log(`Customer service processed: ${message.action}`);
        resolve({ status: 'success', processedAt: new Date() });
      }, 75);
    });
  }

  // Utility methods
  calculateEventPriority(changeDoc) {
    // Priority scoring based on operation type and document characteristics
    const basePriority = {
      'insert': 10,
      'update': 5,
      'delete': 15,
      'replace': 8
    };

    let priority = basePriority[changeDoc.operationType] || 1;

    // Boost priority for high-value orders
    if (changeDoc.fullDocument?.total_amount > 1000) {
      priority += 5;
    }

    // Boost priority for status changes
    if (changeDoc.updateDescription?.updatedFields?.status) {
      priority += 3;
    }

    return priority;
  }

  generateCorrelationId(changeDoc) {
    return `${changeDoc.operationType}-${changeDoc.documentKey._id}-${Date.now()}`;
  }

  generateTraceId() {
    return require('crypto').randomUUID();
  }

  updateStreamStats(streamName, event) {
    const streamData = this.changeStreams.get(streamName);
    if (streamData) {
      streamData.stats.lastEventTime = new Date();

      switch (event) {
        case 'event_received':
          streamData.stats.eventsProcessed++;
          break;
        case 'error':
        case 'stream_error':
          streamData.stats.errors++;
          break;
      }
    }
  }

  updateProcessingMetrics(streamName, processingTime, success) {
    if (!this.processingStats.has(streamName)) {
      this.processingStats.set(streamName, {
        totalProcessed: 0,
        totalErrors: 0,
        totalProcessingTime: 0,
        avgProcessingTime: 0
      });
    }

    const stats = this.processingStats.get(streamName);

    if (success) {
      stats.totalProcessed++;
      stats.totalProcessingTime += processingTime;
      stats.avgProcessingTime = stats.totalProcessingTime / stats.totalProcessed;
    } else {
      stats.totalErrors++;
    }
  }

  getStreamStatus() {
    const status = {
      activeStreams: this.changeStreams.size,
      totalEventsProcessed: 0,
      totalErrors: 0,
      streams: {}
    };

    for (const [streamName, streamData] of this.changeStreams) {
      status.totalEventsProcessed += streamData.stats.eventsProcessed;
      status.totalErrors += streamData.stats.errors;

      status.streams[streamName] = {
        collection: streamData.collection,
        eventsProcessed: streamData.stats.eventsProcessed,
        errors: streamData.stats.errors,
        uptime: Date.now() - streamData.stats.startTime.getTime(),
        lastEventTime: streamData.stats.lastEventTime
      };
    }

    return status;
  }

  async resumeChangeStream(streamName) {
    const streamData = this.changeStreams.get(streamName);
    if (!streamData) return;

    console.log(`Resuming change stream: ${streamName}`);

    try {
      // Close current stream
      await streamData.stream.close();

      // Create new stream with resume token
      const resumeToken = this.resumeTokens.get(streamName);
      const config = {
        ...streamData.config,
        resumeToken: resumeToken
      };

      await this.createChangeStream(streamName, config);
      console.log(`Change stream ${streamName} resumed successfully`);

    } catch (error) {
      console.error(`Failed to resume change stream ${streamName}:`, error);
      this.emit('resume_failed', { streamName, error });
    }
  }

  async close() {
    console.log('Closing all change streams...');

    for (const [streamName, streamData] of this.changeStreams) {
      try {
        await streamData.stream.close();
        console.log(`Closed change stream: ${streamName}`);
      } catch (error) {
        console.error(`Error closing stream ${streamName}:`, error);
      }
    }

    this.changeStreams.clear();
    this.resumeTokens.clear();
    console.log('All change streams closed');
  }
}

// Example usage: Complete microservices coordination system
async function setupEcommerceEventProcessing() {
  console.log('Setting up comprehensive e-commerce event processing system...');

  const changeStreamManager = new MongoChangeStreamManager(db);

  // Configure change streams for different aspects of the system
  const streamConfigurations = {
    // Order lifecycle management
    orderEvents: {
      collection: 'orders',
      operationTypes: ['insert', 'update', 'delete'],
      processor: changeStreamManager.eventProcessors.get('orderLifecycle'),
      options: {
        fullDocument: 'updateLookup',
        fullDocumentBeforeChange: 'whenAvailable'
      }
    },

    // Inventory synchronization
    inventorySync: {
      collection: 'orders',
      operationTypes: ['insert', 'update'],
      documentFilter: {
        $or: [
          { operationType: 'insert' },
          { 'updateDescription.updatedFields.status': { $exists: true } }
        ]
      },
      processor: changeStreamManager.eventProcessors.get('inventorySync')
    },

    // Real-time analytics
    analyticsEvents: {
      collection: 'orders',
      processor: changeStreamManager.eventProcessors.get('realTimeAnalytics'),
      options: {
        fullDocument: 'updateLookup'
      }
    },

    // Customer engagement
    customerEngagement: {
      collection: 'orders',
      operationTypes: ['insert', 'update'],
      processor: changeStreamManager.eventProcessors.get('customerEngagement'),
      options: {
        fullDocument: 'updateLookup'
      }
    },

    // User profile updates
    userProfileSync: {
      collection: 'users',
      operationTypes: ['update'],
      documentFilter: {
        'updateDescription.updatedFields': {
          $or: [
            { 'email': { $exists: true } },
            { 'profile': { $exists: true } },
            { 'preferences': { $exists: true } }
          ]
        }
      },
      processor: async (context) => {
        console.log(`User profile updated: ${context.getDocumentId()}`);
        // Sync profile changes across microservices
        await changeStreamManager.notifyCustomerService({
          action: 'profile_sync',
          userId: context.getDocumentId(),
          changes: context.updateDescription.updatedFields
        });
      }
    }
  };

  // Initialize all change streams
  await changeStreamManager.initializeChangeStreams(streamConfigurations);

  // Monitor system health
  setInterval(() => {
    const status = changeStreamManager.getStreamStatus();
    console.log('Change Stream System Status:', JSON.stringify(status, null, 2));
  }, 30000); // Every 30 seconds

  return changeStreamManager;
}

// Benefits of MongoDB Change Streams:
// - Real-time, ordered change events with guaranteed delivery
// - Resume capability from any point using resume tokens
// - Rich filtering and transformation capabilities through aggregation pipelines
// - Automatic failover and reconnection handling
// - Document-level granularity with full document context
// - Cluster-wide change tracking across replica sets and sharded clusters
// - Built-in support for microservices coordination patterns
// - Efficient resource utilization without polling overhead
// - Comprehensive event metadata and processing context
// - SQL-compatible change processing through QueryLeaf integration

module.exports = {
  MongoChangeStreamManager,
  setupEcommerceEventProcessing
};

Understanding MongoDB Change Streams Architecture

Advanced Event-Driven Patterns and Microservices Coordination

Implement sophisticated change stream patterns for production-scale event processing:

// Production-grade change stream patterns for enterprise applications
class EnterpriseChangeStreamManager extends MongoChangeStreamManager {
  constructor(db, enterpriseConfig) {
    super(db);

    this.enterpriseConfig = {
      messageQueue: enterpriseConfig.messageQueue, // RabbitMQ, Kafka, etc.
      distributedTracing: enterpriseConfig.distributedTracing,
      metricsCollector: enterpriseConfig.metricsCollector,
      errorReporting: enterpriseConfig.errorReporting,
      circuitBreaker: enterpriseConfig.circuitBreaker
    };

    this.setupEnterpriseIntegrations();
  }

  async setupMultiTenantChangeStreams(tenantConfigurations) {
    console.log('Setting up multi-tenant change stream architecture...');

    const tenantStreams = new Map();

    for (const [tenantId, config] of Object.entries(tenantConfigurations)) {
      const tenantStreamConfig = {
        ...config,
        pipeline: [
          { $match: { 'fullDocument.tenant_id': tenantId } },
          ...(config.pipeline || [])
        ],
        processor: this.createTenantProcessor(tenantId, config.processor)
      };

      const streamName = `tenant_${tenantId}_${config.name}`;
      tenantStreams.set(streamName, tenantStreamConfig);
    }

    await this.initializeChangeStreams(Object.fromEntries(tenantStreams));
    return tenantStreams;
  }

  createTenantProcessor(tenantId, baseProcessor) {
    return async (context) => {
      // Add tenant context
      const tenantContext = {
        ...context,
        tenantId: tenantId,
        tenantConfig: await this.getTenantConfig(tenantId)
      };

      // Execute with tenant-specific error handling
      try {
        await baseProcessor(tenantContext);
      } catch (error) {
        await this.handleTenantError(tenantId, error, context);
      }
    };
  }

  async implementEventSourcingPattern(aggregateConfigs) {
    console.log('Implementing event sourcing pattern with change streams...');

    const eventSourcingStreams = {};

    for (const [aggregateName, config] of Object.entries(aggregateConfigs)) {
      eventSourcingStreams[`${aggregateName}_events`] = {
        collection: config.collection,
        operationTypes: ['insert', 'update', 'delete'],
        processor: async (context) => {
          const event = this.buildDomainEvent(aggregateName, context);

          // Store in event store
          await this.appendToEventStore(event);

          // Update projections
          await this.updateProjections(aggregateName, event);

          // Publish to event bus
          await this.publishDomainEvent(event);
        },
        options: {
          fullDocument: 'updateLookup',
          fullDocumentBeforeChange: 'whenAvailable'
        }
      };
    }

    return eventSourcingStreams;
  }

  buildDomainEvent(aggregateName, context) {
    const { operation, document, documentKey, updateDescription, timestamp } = context;

    return {
      eventId: require('crypto').randomUUID(),
      eventType: `${aggregateName}.${operation}`,
      aggregateId: documentKey._id,
      aggregateType: aggregateName,
      eventData: {
        before: context.fullDocumentBeforeChange,
        after: document,
        changes: updateDescription
      },
      eventMetadata: {
        timestamp: timestamp,
        causationId: context.metadata.correlationId,
        correlationId: context.metadata.traceId,
        userId: document?.user_id || 'system',
        version: await this.getAggregateVersion(aggregateName, documentKey._id)
      }
    };
  }

  async setupCQRSIntegration(cqrsConfig) {
    console.log('Setting up CQRS integration with change streams...');

    const cqrsStreams = {};

    // Command side - write model changes
    for (const [commandModel, config] of Object.entries(cqrsConfig.commandModels)) {
      cqrsStreams[`${commandModel}_commands`] = {
        collection: config.collection,
        processor: async (context) => {
          // Update read models
          await this.updateReadModels(commandModel, context);

          // Invalidate caches
          await this.invalidateReadModelCaches(commandModel, context.getDocumentId());

          // Publish integration events
          await this.publishIntegrationEvents(commandModel, context);
        }
      };
    }

    return cqrsStreams;
  }

  async setupDistributedSagaCoordination(sagaConfigurations) {
    console.log('Setting up distributed saga coordination...');

    const sagaStreams = {};

    for (const [sagaName, config] of Object.entries(sagaConfigurations)) {
      sagaStreams[`${sagaName}_saga`] = {
        collection: config.triggerCollection,
        documentFilter: config.triggerFilter,
        processor: async (context) => {
          const sagaInstance = await this.createSagaInstance(sagaName, context);
          await this.executeSagaStep(sagaInstance, context);
        }
      };
    }

    return sagaStreams;
  }

  async createSagaInstance(sagaName, triggerContext) {
    const sagaInstance = {
      sagaId: require('crypto').randomUUID(),
      sagaType: sagaName,
      status: 'started',
      currentStep: 0,
      triggerEvent: {
        aggregateId: triggerContext.getDocumentId(),
        eventData: triggerContext.document
      },
      compensation: [],
      createdAt: new Date()
    };

    await this.db.collection('saga_instances').insertOne(sagaInstance);
    return sagaInstance;
  }

  async setupAdvancedMonitoring() {
    console.log('Setting up advanced change stream monitoring...');

    const monitoringConfig = {
      healthChecks: {
        streamLiveness: true,
        processingLatency: true,
        errorRates: true,
        throughput: true
      },

      alerting: {
        streamFailure: { threshold: 1, window: '1m' },
        highLatency: { threshold: 5000, window: '5m' },
        errorRate: { threshold: 0.05, window: '10m' },
        lowThroughput: { threshold: 10, window: '5m' }
      },

      metrics: {
        prometheus: true,
        cloudwatch: false,
        datadog: false
      }
    };

    return this.initializeMonitoring(monitoringConfig);
  }
}

SQL-Style Change Stream Processing with QueryLeaf

QueryLeaf provides familiar SQL syntax for MongoDB change stream configuration and event processing:

-- QueryLeaf change stream management with SQL-familiar patterns

-- Create comprehensive change stream for order processing
CREATE CHANGE STREAM order_processing_stream ON orders
WATCH FOR (INSERT, UPDATE, DELETE)
WHERE 
  status IN ('pending', 'confirmed', 'shipped', 'delivered', 'cancelled')
  AND total_amount > 0
WITH OPTIONS (
  full_document = 'updateLookup',
  full_document_before_change = 'whenAvailable',
  batch_size = 100,
  max_await_time = 1000,
  start_at_operation_time = CURRENT_TIMESTAMP - INTERVAL '1 hour'
)
PROCESS WITH order_lifecycle_handler;

-- Advanced change stream with complex filtering and transformation
CREATE CHANGE STREAM high_value_order_stream ON orders
WATCH FOR (INSERT, UPDATE)
WHERE 
  operationType = 'insert' AND fullDocument.total_amount >= 1000
  OR (operationType = 'update' AND updateDescription.updatedFields.status EXISTS)
WITH PIPELINE (
  -- Stage 1: Additional filtering
  {
    $match: {
      $or: [
        { 
          operationType: 'insert',
          'fullDocument.customer_tier': { $in: ['gold', 'platinum'] }
        },
        {
          operationType: 'update',
          'fullDocument.total_amount': { $gte: 1000 }
        }
      ]
    }
  },

  -- Stage 2: Enrich with customer data
  {
    $lookup: {
      from: 'users',
      localField: 'fullDocument.user_id',
      foreignField: '_id',
      as: 'customer_data',
      pipeline: [
        {
          $project: {
            email: 1,
            customer_tier: 1,
            lifetime_value: 1,
            preferences: 1
          }
        }
      ]
    }
  },

  -- Stage 3: Calculate priority score
  {
    $addFields: {
      processing_priority: {
        $switch: {
          branches: [
            { 
              case: { $gte: ['$fullDocument.total_amount', 5000] }, 
              then: 'critical' 
            },
            { 
              case: { $gte: ['$fullDocument.total_amount', 2000] }, 
              then: 'high' 
            },
            { 
              case: { $gte: ['$fullDocument.total_amount', 1000] }, 
              then: 'medium' 
            }
          ],
          default: 'normal'
        }
      }
    }
  }
)
PROCESS WITH vip_order_processor;

-- Real-time analytics change stream with aggregation
CREATE MATERIALIZED CHANGE STREAM real_time_order_metrics ON orders
WATCH FOR (INSERT, UPDATE, DELETE)
WITH AGGREGATION (
  -- Group by time buckets for real-time metrics
  GROUP BY (
    DATE_TRUNC('minute', clusterTime, 5) as time_bucket,
    fullDocument.region as region
  )
  SELECT 
    time_bucket,
    region,

    -- Real-time KPIs
    COUNT(*) FILTER (WHERE operationType = 'insert') as new_orders,
    COUNT(*) FILTER (WHERE operationType = 'update' AND updateDescription.updatedFields.status = 'shipped') as orders_shipped,
    COUNT(*) FILTER (WHERE operationType = 'delete') as orders_cancelled,

    -- Revenue metrics
    SUM(fullDocument.total_amount) FILTER (WHERE operationType = 'insert') as new_revenue,
    AVG(fullDocument.total_amount) FILTER (WHERE operationType = 'insert') as avg_order_value,

    -- Customer metrics
    COUNT(DISTINCT fullDocument.user_id) as unique_customers,

    -- Performance indicators
    COUNT(*) / 5.0 as events_per_minute,
    CURRENT_TIMESTAMP as computed_at

  WINDOW (
    ORDER BY time_bucket
    ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
  )
  ADD (
    AVG(new_orders) OVER window as rolling_avg_orders,
    AVG(new_revenue) OVER window as rolling_avg_revenue,

    -- Trend detection
    CASE 
      WHEN new_orders > rolling_avg_orders * 1.2 THEN 'surge'
      WHEN new_orders < rolling_avg_orders * 0.8 THEN 'decline'
      ELSE 'stable'
    END as order_trend
  )
)
REFRESH EVERY 5 SECONDS
PROCESS WITH analytics_event_handler;

-- Customer segmentation change stream with RFM analysis
CREATE CHANGE STREAM customer_behavior_analysis ON orders
WATCH FOR (INSERT, UPDATE)
WHERE fullDocument.status IN ('completed', 'delivered')
WITH CUSTOMER_SEGMENTATION (
  -- Calculate RFM metrics from change events
  SELECT 
    fullDocument.user_id as customer_id,

    -- Recency calculation
    EXTRACT(DAYS FROM CURRENT_TIMESTAMP - MAX(fullDocument.order_date)) as recency_days,

    -- Frequency calculation  
    COUNT(*) FILTER (WHERE operationType = 'insert') as order_frequency,

    -- Monetary calculation
    SUM(fullDocument.total_amount) as total_monetary_value,
    AVG(fullDocument.total_amount) as avg_order_value,

    -- Advanced behavior metrics
    COUNT(DISTINCT fullDocument.product_categories) as category_diversity,
    AVG(ARRAY_LENGTH(fullDocument.items)) as avg_items_per_order,

    -- Engagement patterns
    COUNT(*) FILTER (WHERE EXTRACT(DOW FROM fullDocument.order_date) IN (0, 6)) / COUNT(*)::float as weekend_preference,

    -- RFM scoring
    NTILE(5) OVER (ORDER BY recency_days DESC) as recency_score,
    NTILE(5) OVER (ORDER BY order_frequency ASC) as frequency_score,  
    NTILE(5) OVER (ORDER BY total_monetary_value ASC) as monetary_score,

    -- Customer segment classification
    CASE 
      WHEN NTILE(5) OVER (ORDER BY recency_days DESC) >= 4 
           AND NTILE(5) OVER (ORDER BY order_frequency ASC) >= 4 
           AND NTILE(5) OVER (ORDER BY total_monetary_value ASC) >= 4 THEN 'champions'
      WHEN NTILE(5) OVER (ORDER BY recency_days DESC) >= 3 
           AND NTILE(5) OVER (ORDER BY order_frequency ASC) >= 3 
           AND NTILE(5) OVER (ORDER BY total_monetary_value ASC) >= 3 THEN 'loyal_customers'
      WHEN NTILE(5) OVER (ORDER BY recency_days DESC) >= 4 
           AND NTILE(5) OVER (ORDER BY order_frequency ASC) <= 2 THEN 'potential_loyalists'
      WHEN NTILE(5) OVER (ORDER BY recency_days DESC) >= 4 
           AND NTILE(5) OVER (ORDER BY order_frequency ASC) <= 1 THEN 'new_customers'
      WHEN NTILE(5) OVER (ORDER BY recency_days DESC) <= 2 
           AND NTILE(5) OVER (ORDER BY order_frequency ASC) >= 3 THEN 'at_risk'
      ELSE 'needs_attention'
    END as customer_segment,

    -- Predictive metrics
    total_monetary_value / GREATEST(recency_days / 30.0, 1) * order_frequency as predicted_clv,

    CURRENT_TIMESTAMP as analyzed_at

  GROUP BY fullDocument.user_id
  WINDOW customer_analysis AS (
    PARTITION BY fullDocument.user_id
    ORDER BY fullDocument.order_date
    RANGE BETWEEN INTERVAL '365 days' PRECEDING AND CURRENT ROW
  )
)
PROCESS WITH customer_segmentation_handler;

-- Inventory synchronization change stream
CREATE CHANGE STREAM inventory_sync_stream ON orders  
WATCH FOR (INSERT, UPDATE, DELETE)
WHERE 
  operationType = 'insert' 
  OR (operationType = 'update' AND updateDescription.updatedFields.status EXISTS)
  OR operationType = 'delete'
WITH EVENT_PROCESSING (
  CASE operationType
    WHEN 'insert' THEN 
      CALL reserve_inventory(fullDocument.items, fullDocument._id)
    WHEN 'update' THEN
      CASE updateDescription.updatedFields.status
        WHEN 'cancelled' THEN 
          CALL release_inventory_reservation(fullDocument._id)
        WHEN 'shipped' THEN 
          CALL confirm_inventory_consumption(fullDocument._id)
        WHEN 'returned' THEN 
          CALL restore_inventory(fullDocument.items, fullDocument._id)
      END
    WHEN 'delete' THEN
      CALL cleanup_inventory_reservations(documentKey._id)
  END
)
WITH OPTIONS (
  retry_policy = {
    max_attempts: 3,
    backoff_strategy: 'exponential',
    base_delay: '1 second'
  },
  dead_letter_queue = 'inventory_sync_dlq',
  processing_timeout = '30 seconds'
)
PROCESS WITH inventory_coordination_handler;

-- Microservices event coordination with saga pattern
CREATE DISTRIBUTED SAGA order_fulfillment_saga 
TRIGGERED BY orders.insert
WHERE fullDocument.status = 'pending' AND fullDocument.total_amount > 0
WITH STEPS (
  -- Step 1: Payment processing
  {
    service: 'payment-service',
    action: 'process_payment',
    input: {
      order_id: NEW.documentKey._id,
      amount: NEW.fullDocument.total_amount,
      payment_method: NEW.fullDocument.payment_method
    },
    compensation: {
      service: 'payment-service', 
      action: 'refund_payment',
      input: { payment_id: '${payment_result.payment_id}' }
    },
    timeout: '30 seconds'
  },

  -- Step 2: Inventory reservation
  {
    service: 'inventory-service',
    action: 'reserve_products',
    input: {
      order_id: NEW.documentKey._id,
      items: NEW.fullDocument.items
    },
    compensation: {
      service: 'inventory-service',
      action: 'release_reservation', 
      input: { reservation_id: '${inventory_result.reservation_id}' }
    },
    timeout: '15 seconds'
  },

  -- Step 3: Shipping calculation
  {
    service: 'shipping-service',
    action: 'calculate_shipping',
    input: {
      order_id: NEW.documentKey._id,
      shipping_address: NEW.fullDocument.shipping_address,
      items: NEW.fullDocument.items
    },
    compensation: {
      service: 'shipping-service',
      action: 'cancel_shipping',
      input: { shipping_id: '${shipping_result.shipping_id}' }
    },
    timeout: '10 seconds'
  },

  -- Step 4: Order confirmation
  {
    service: 'notification-service',
    action: 'send_confirmation',
    input: {
      order_id: NEW.documentKey._id,
      customer_email: NEW.fullDocument.customer_email,
      order_details: NEW.fullDocument
    },
    timeout: '5 seconds'
  }
)
WITH SAGA_OPTIONS (
  max_retry_attempts = 3,
  compensation_timeout = '60 seconds',
  saga_timeout = '5 minutes'
);

-- Event sourcing pattern with change streams
CREATE EVENT STORE order_events
FROM CHANGE STREAM orders.*
WITH EVENT_MAPPING (
  event_type = CONCAT('Order.', TITLE_CASE(operationType)),
  aggregate_id = documentKey._id,
  aggregate_type = 'Order',
  event_data = {
    before: fullDocumentBeforeChange,
    after: fullDocument,
    changes: updateDescription
  },
  event_metadata = {
    timestamp: clusterTime,
    causation_id: correlation_id,
    correlation_id: trace_id,
    user_id: COALESCE(fullDocument.user_id, 'system'),
    version: aggregate_version + 1
  }
)
WITH PROJECTIONS (
  -- Order summary projection
  order_summary = {
    aggregate_id: aggregate_id,
    current_status: event_data.after.status,
    total_amount: event_data.after.total_amount,
    created_at: event_data.after.created_at,
    last_updated: event_metadata.timestamp,
    version: event_metadata.version
  },

  -- Customer order history projection  
  customer_orders = {
    customer_id: event_data.after.user_id,
    order_id: aggregate_id,
    order_amount: event_data.after.total_amount,
    order_date: event_data.after.created_at,
    status: event_data.after.status
  }
);

-- Advanced monitoring and alerting for change streams
CREATE CHANGE STREAM MONITOR comprehensive_monitoring
WITH METRICS (
  -- Stream health metrics
  stream_uptime,
  events_processed_per_second,
  processing_latency_p95,
  error_rate,
  resume_token_age,

  -- Business metrics
  high_value_orders_per_minute,
  average_processing_time,
  failed_event_count,

  -- System resource metrics
  memory_usage,
  cpu_utilization,
  network_throughput
)
WITH ALERTS (
  -- Critical alerts
  stream_disconnected = {
    condition: stream_uptime = 0,
    severity: 'critical',
    notification: ['pager', 'slack:#ops-critical']
  },

  high_error_rate = {
    condition: error_rate > 0.05 FOR 5 MINUTES,
    severity: 'high', 
    notification: ['email:[email protected]', 'slack:#database-alerts']
  },

  processing_latency = {
    condition: processing_latency_p95 > 5000 FOR 3 MINUTES,
    severity: 'medium',
    notification: ['slack:#performance-alerts']
  },

  -- Business alerts
  revenue_drop = {
    condition: high_value_orders_per_minute < 10 FOR 10 MINUTES DURING BUSINESS_HOURS,
    severity: 'high',
    notification: ['email:[email protected]']
  }
);

-- QueryLeaf provides comprehensive change stream capabilities:
-- 1. SQL-familiar syntax for MongoDB change stream creation and management
-- 2. Advanced filtering and transformation through aggregation pipelines
-- 3. Real-time analytics and materialized views from change events
-- 4. Customer segmentation and behavioral analysis integration
-- 5. Microservices coordination with distributed saga patterns
-- 6. Event sourcing and CQRS implementation support
-- 7. Comprehensive monitoring and alerting for production environments
-- 8. Inventory synchronization and business process automation
-- 9. Multi-tenant and enterprise-grade change stream management
-- 10. Integration with external message queues and event systems

Best Practices for Change Stream Implementation

Event-Driven Architecture Design

Essential principles for building robust change stream-based systems:

  1. Resume Token Management: Always store resume tokens for fault tolerance and recovery
  2. Event Processing Idempotency: Design event processors to handle duplicate events gracefully
  3. Error Handling Strategy: Implement comprehensive error handling with retry policies and dead letter queues
  4. Filtering Optimization: Use early filtering in change stream pipelines to reduce processing overhead
  5. Resource Management: Monitor and manage memory usage for long-running change streams
  6. Monitoring Integration: Implement comprehensive monitoring for stream health and processing metrics

Production Deployment Strategies

Optimize change stream deployments for production-scale environments:

  1. High Availability: Deploy change stream processors across multiple instances with proper load balancing
  2. Scaling Patterns: Implement horizontal scaling strategies for high-throughput scenarios
  3. Performance Monitoring: Track processing latency, throughput, and error rates continuously
  4. Security Considerations: Ensure proper authentication and authorization for change stream access
  5. Backup and Recovery: Implement comprehensive backup strategies for resume tokens and processing state
  6. Integration Testing: Thoroughly test change stream integrations with downstream systems

Conclusion

MongoDB Change Streams provide a powerful foundation for building sophisticated event-driven architectures that enable real-time data processing, microservices coordination, and reactive application patterns. The ordered, resumable stream of change events eliminates the complexity and limitations of traditional change detection approaches while providing comprehensive filtering, transformation, and integration capabilities.

Key MongoDB Change Streams benefits include:

  • Real-time Processing: Immediate notification of data changes without polling overhead
  • Fault Tolerance: Resume capability from any point using resume tokens with guaranteed delivery
  • Rich Context: Complete document context with before/after states for comprehensive processing
  • Scalable Architecture: Horizontal scaling support for high-throughput event processing scenarios
  • Microservices Integration: Native support for distributed system coordination and communication patterns
  • Flexible Filtering: Advanced aggregation pipeline integration for sophisticated event filtering and transformation

Whether you're building real-time analytics platforms, microservices architectures, event sourcing systems, or reactive applications, MongoDB Change Streams with QueryLeaf's familiar SQL interface provide the foundation for modern event-driven development.

QueryLeaf Integration: QueryLeaf automatically manages MongoDB change stream operations while providing SQL-familiar syntax for event processing, microservices coordination, and real-time analytics. Advanced change stream patterns, saga orchestration, and event sourcing capabilities are seamlessly accessible through familiar SQL constructs, making sophisticated event-driven architectures both powerful and approachable for SQL-oriented development teams.

The combination of MongoDB's robust change stream capabilities with SQL-style operations makes it an ideal platform for modern applications requiring real-time responsiveness and distributed system coordination, ensuring your event-driven architectures can scale efficiently while maintaining consistency and reliability across complex distributed topologies.

MongoDB Indexing Strategies and Compound Indexes: Advanced Performance Optimization for Scalable Database Operations

Database performance at scale depends heavily on effective indexing strategies that can efficiently support diverse query patterns while minimizing storage overhead and maintenance costs. Poor indexing decisions lead to slow query performance, excessive resource consumption, and degraded user experience that becomes increasingly problematic as data volumes and application complexity grow.

MongoDB's sophisticated indexing system provides comprehensive support for simple and compound indexes, partial filters, text search indexes, and specialized data type indexes that enable developers to optimize query performance for complex application requirements. Unlike traditional database systems with rigid indexing constraints, MongoDB's flexible indexing architecture supports dynamic schema requirements while providing powerful optimization capabilities through compound indexes, index intersection, and advanced filtering strategies.

The Traditional Database Indexing Limitations

Conventional database indexing approaches often struggle with complex query patterns and multi-dimensional data access requirements:

-- Traditional PostgreSQL indexing with limited flexibility and optimization challenges

-- Basic single-column indexes with poor compound query support
CREATE INDEX idx_users_email ON users (email);
CREATE INDEX idx_users_status ON users (status);
CREATE INDEX idx_users_created_at ON users (created_at);
CREATE INDEX idx_users_country ON users (country);

-- Simple compound index with fixed column order limitations
CREATE INDEX idx_users_status_country ON users (status, country);

-- Complex query requiring multiple index scans and poor optimization
SELECT 
  u.user_id,
  u.email,
  u.first_name,
  u.last_name,
  u.status,
  u.country,
  u.created_at,
  u.last_login_at,
  COUNT(o.order_id) as order_count,
  SUM(o.total_amount) as total_spent,
  MAX(o.order_date) as last_order_date
FROM users u
LEFT JOIN orders o ON u.user_id = o.user_id
WHERE u.status IN ('active', 'premium', 'trial')
  AND u.country IN ('US', 'CA', 'UK', 'AU', 'DE', 'FR')
  AND u.created_at >= CURRENT_DATE - INTERVAL '2 years'
  AND u.last_login_at >= CURRENT_DATE - INTERVAL '30 days'
  AND (u.email LIKE '%@gmail.com' OR u.email LIKE '%@hotmail.com')
  AND u.subscription_tier IS NOT NULL
GROUP BY u.user_id, u.email, u.first_name, u.last_name, u.status, u.country, u.created_at, u.last_login_at
HAVING COUNT(o.order_id) > 0
ORDER BY total_spent DESC, last_order_date DESC
LIMIT 100;

-- PostgreSQL EXPLAIN showing inefficient index usage:
-- 
-- Limit  (cost=45234.67..45234.92 rows=100 width=128) (actual time=1247.123..1247.189 rows=100 loops=1)
--   ->  Sort  (cost=45234.67..45789.23 rows=221824 width=128) (actual time=1247.121..1247.156 rows=100 loops=1)
--         Sort Key: (sum(o.total_amount)) DESC, (max(o.order_date)) DESC
--         Sort Method: top-N heapsort  Memory: 67kB
--         ->  HashAggregate  (cost=38234.56..40456.80 rows=221824 width=128) (actual time=1156.789..1201.234 rows=12789 loops=1)
--               Group Key: u.user_id, u.email, u.first_name, u.last_name, u.status, u.country, u.created_at, u.last_login_at
--               ->  Hash Left Join  (cost=12345.67..32890.45 rows=221824 width=96) (actual time=89.456..567.123 rows=87645 loops=1)
--                     Hash Cond: (u.user_id = o.user_id)
--                     ->  Bitmap Heap Scan on users u  (cost=3456.78..8901.23 rows=45678 width=88) (actual time=34.567..123.456 rows=23456 loops=1)
--                           Recheck Cond: ((status = ANY ('{active,premium,trial}'::text[])) AND 
--                                         (country = ANY ('{US,CA,UK,AU,DE,FR}'::text[])) AND 
--                                         (created_at >= (CURRENT_DATE - '2 years'::interval)) AND 
--                                         (last_login_at >= (CURRENT_DATE - '30 days'::interval)))
--                           Filter: ((subscription_tier IS NOT NULL) AND 
--                                   ((email ~~ '%@gmail.com'::text) OR (email ~~ '%@hotmail.com'::text)))
--                           Rows Removed by Filter: 12789
--                           Heap Blocks: exact=1234 lossy=234
--                           ->  BitmapOr  (cost=3456.78..3456.78 rows=45678 width=0) (actual time=33.890..33.891 rows=0 loops=1)
--                                 ->  Bitmap Index Scan on idx_users_status_country  (cost=0.00..1234.56 rows=15678 width=0) (actual time=12.345..12.345 rows=18901 loops=1)
--                                       Index Cond: ((status = ANY ('{active,premium,trial}'::text[])) AND 
--                                                   (country = ANY ('{US,CA,UK,AU,DE,FR}'::text[])))
--                                 ->  Bitmap Index Scan on idx_users_created_at  (cost=0.00..1890.23 rows=25678 width=0) (actual time=18.234..18.234 rows=34567 loops=1)
--                                       Index Cond: (created_at >= (CURRENT_DATE - '2 years'::interval))
--                                 ->  Bitmap Index Scan on idx_users_last_login  (cost=0.00..331.99 rows=4322 width=0) (actual time=3.311..3.311 rows=8765 loops=1)
--                                       Index Cond: (last_login_at >= (CURRENT_DATE - '30 days'::interval))
--                     ->  Hash  (cost=7890.45..7890.45 rows=234567 width=24) (actual time=54.889..54.889 rows=198765 loops=1)
--                           Buckets: 262144  Batches: 1  Memory Usage: 11234kB
--                           ->  Seq Scan on orders o  (cost=0.00..7890.45 rows=234567 width=24) (actual time=0.234..28.901 rows=198765 loops=1)
-- Planning Time: 4.567 ms
-- Execution Time: 1247.567 ms

-- Problems with traditional PostgreSQL indexing:
-- 1. Multiple bitmap index scans required due to lack of comprehensive compound index
-- 2. Expensive BitmapOr operations combining multiple index results
-- 3. Large number of rows removed by filter conditions not supported by indexes
-- 4. Complex compound indexes difficult to design for multiple query patterns
-- 5. Index bloat and maintenance overhead with many single-column indexes
-- 6. Poor support for partial indexes and conditional filtering
-- 7. Limited flexibility in query optimization and index selection
-- 8. Difficulty optimizing for mixed equality/range/pattern matching conditions

-- Attempt to create better compound index
CREATE INDEX idx_users_comprehensive ON users (
  status, country, created_at, last_login_at, subscription_tier, email
);

-- Problems with large compound indexes:
-- 1. Index becomes very large and expensive to maintain
-- 2. Only efficient for queries that follow exact prefix patterns
-- 3. Wasted space for queries that don't use all index columns
-- 4. Update performance degradation due to large index maintenance
-- 5. Limited effectiveness for partial field matching (email patterns)
-- 6. Poor selectivity when early columns have low cardinality

-- MySQL limitations are even more restrictive
CREATE INDEX idx_users_limited ON users (status, country, created_at);
-- MySQL compound index limitations:
-- - Maximum 16 columns per compound index
-- - 767 bytes total key length limit (InnoDB)
-- - Poor optimization for range queries on non-leading columns
-- - Limited partial index support
-- - Inefficient covering index implementation
-- - Basic query optimizer with limited compound index utilization

-- Alternative approach with covering indexes (PostgreSQL)
CREATE INDEX idx_users_covering ON users (status, country, created_at) 
INCLUDE (email, first_name, last_name, last_login_at, subscription_tier);

-- Covering index problems:
-- 1. Large storage overhead for included columns
-- 2. Still limited by leading column selectivity
-- 3. Expensive maintenance operations
-- 4. Complex index design decisions
-- 5. Poor performance for non-matching query patterns

MongoDB provides sophisticated compound indexing with flexible optimization:

// MongoDB Advanced Indexing Strategies - comprehensive compound index management and optimization
const { MongoClient } = require('mongodb');

const client = new MongoClient('mongodb://localhost:27017');
const db = client.db('advanced_ecommerce_platform');

// Advanced MongoDB indexing strategy and compound index optimization system
class MongoIndexOptimizer {
  constructor(db) {
    this.db = db;
    this.collections = {
      users: db.collection('users'),
      orders: db.collection('orders'),
      products: db.collection('products'),
      analytics: db.collection('analytics'),
      sessions: db.collection('sessions')
    };

    // Index optimization configuration
    this.indexingStrategies = {
      equalityFirst: true,        // ESR pattern - Equality, Sort, Range
      sortOptimization: true,     // Optimize for sort operations
      partialIndexes: true,       // Use partial indexes for selective filtering
      coveringIndexes: true,      // Create covering indexes where beneficial
      textSearchIndexes: true,    // Advanced text search capabilities
      geospatialIndexes: true,    // Location-based indexing
      ttlIndexes: true           // Time-based data expiration
    };

    this.performanceTargets = {
      maxQueryTimeMs: 100,
      minIndexSelectivity: 0.1,
      maxIndexSizeMB: 500,
      maxIndexesPerCollection: 10
    };

    this.indexAnalytics = new Map();
  }

  async implementComprehensiveIndexingStrategy(collectionName, queryPatterns) {
    console.log(`Implementing comprehensive indexing strategy for ${collectionName}...`);

    const collection = this.collections[collectionName];
    const existingIndexes = await collection.listIndexes().toArray();

    const indexingPlan = {
      collection: collectionName,
      queryPatterns: queryPatterns,
      existingIndexes: existingIndexes,
      recommendedIndexes: [],
      optimizationActions: [],
      performanceProjections: {}
    };

    // Analyze query patterns for optimal index design
    const queryAnalysis = await this.analyzeQueryPatterns(queryPatterns);

    // Generate compound index recommendations
    const compoundIndexes = await this.generateCompoundIndexes(queryAnalysis);

    // Design partial indexes for selective filtering
    const partialIndexes = await this.generatePartialIndexes(queryAnalysis);

    // Create covering indexes for frequently accessed projections
    const coveringIndexes = await this.generateCoveringIndexes(queryAnalysis);

    // Specialized indexes for specific data types and operations
    const specializedIndexes = await this.generateSpecializedIndexes(queryAnalysis);

    indexingPlan.recommendedIndexes = [
      ...compoundIndexes,
      ...partialIndexes, 
      ...coveringIndexes,
      ...specializedIndexes
    ];

    // Validate index recommendations against performance targets
    const validatedPlan = await this.validateIndexingPlan(collection, indexingPlan);

    // Execute index creation with comprehensive monitoring
    const implementationResult = await this.executeIndexingPlan(collection, validatedPlan);

    // Performance validation and optimization
    const performanceValidation = await this.validateIndexPerformance(collection, validatedPlan, queryPatterns);

    return {
      plan: validatedPlan,
      implementation: implementationResult,
      performance: performanceValidation,
      summary: {
        totalIndexes: validatedPlan.recommendedIndexes.length,
        compoundIndexes: compoundIndexes.length,
        partialIndexes: partialIndexes.length,
        coveringIndexes: coveringIndexes.length,
        specializedIndexes: specializedIndexes.length,
        estimatedPerformanceImprovement: this.calculatePerformanceImprovement(validatedPlan)
      }
    };
  }

  async analyzeQueryPatterns(queryPatterns) {
    console.log(`Analyzing ${queryPatterns.length} query patterns for index optimization...`);

    const analysis = {
      fieldUsage: new Map(),           // How often each field is used
      fieldCombinations: new Map(),    // Common field combinations
      filterTypes: new Map(),          // Types of filters (equality, range, etc.)
      sortPatterns: new Map(),         // Sort field combinations
      projectionPatterns: new Map(),   // Frequently requested projections
      selectivityEstimates: new Map()  // Estimated field selectivity
    };

    for (const pattern of queryPatterns) {
      // Analyze filter conditions
      this.analyzeFilterConditions(pattern.filter || {}, analysis);

      // Analyze sort requirements
      this.analyzeSortPatterns(pattern.sort || {}, analysis);

      // Analyze projection requirements
      this.analyzeProjectionPatterns(pattern.projection || {}, analysis);

      // Track query frequency for weighting
      const frequency = pattern.frequency || 1;
      this.updateFrequencyWeights(analysis, frequency);
    }

    // Calculate field selectivity estimates
    await this.estimateFieldSelectivity(analysis);

    // Identify optimal field combinations
    const optimalCombinations = this.identifyOptimalFieldCombinations(analysis);

    return {
      ...analysis,
      optimalCombinations: optimalCombinations,
      indexingRecommendations: this.generateIndexingRecommendations(analysis, optimalCombinations)
    };
  }

  analyzeFilterConditions(filter, analysis) {
    Object.entries(filter).forEach(([field, condition]) => {
      if (field.startsWith('$')) return; // Skip operators

      // Track field usage frequency
      const currentUsage = analysis.fieldUsage.get(field) || 0;
      analysis.fieldUsage.set(field, currentUsage + 1);

      // Categorize filter types
      const filterType = this.categorizeFilterType(condition);
      const currentFilterTypes = analysis.filterTypes.get(field) || new Set();
      currentFilterTypes.add(filterType);
      analysis.filterTypes.set(field, currentFilterTypes);

      // Track field combinations for compound indexes
      const otherFields = Object.keys(filter).filter(f => f !== field && !f.startsWith('$'));
      if (otherFields.length > 0) {
        const combination = [field, ...otherFields].sort().join(',');
        const currentCombinations = analysis.fieldCombinations.get(combination) || 0;
        analysis.fieldCombinations.set(combination, currentCombinations + 1);
      }
    });
  }

  categorizeFilterType(condition) {
    if (typeof condition === 'object' && condition !== null) {
      const operators = Object.keys(condition);

      if (operators.includes('$gte') || operators.includes('$gt') || 
          operators.includes('$lte') || operators.includes('$lt')) {
        return 'range';
      } else if (operators.includes('$in')) {
        return condition.$in.length <= 10 ? 'selective_in' : 'large_in';
      } else if (operators.includes('$regex')) {
        return 'pattern_match';
      } else if (operators.includes('$exists')) {
        return 'existence';
      } else if (operators.includes('$ne')) {
        return 'negation';
      } else {
        return 'complex';
      }
    } else {
      return 'equality';
    }
  }

  analyzeSortPatterns(sort, analysis) {
    if (Object.keys(sort).length === 0) return;

    const sortKey = Object.entries(sort)
      .map(([field, direction]) => `${field}:${direction}`)
      .join(',');

    const currentSort = analysis.sortPatterns.get(sortKey) || 0;
    analysis.sortPatterns.set(sortKey, currentSort + 1);
  }

  analyzeProjectionPatterns(projection, analysis) {
    if (!projection || Object.keys(projection).length === 0) return;

    const projectedFields = Object.keys(projection).filter(field => projection[field] === 1);
    const projectionKey = projectedFields.sort().join(',');

    if (projectionKey) {
      const currentProjection = analysis.projectionPatterns.get(projectionKey) || 0;
      analysis.projectionPatterns.set(projectionKey, currentProjection + 1);
    }
  }

  async generateCompoundIndexes(analysis) {
    console.log('Generating optimal compound index recommendations...');

    const compoundIndexes = [];

    // Sort field combinations by frequency and potential impact
    const sortedCombinations = Array.from(analysis.fieldCombinations.entries())
      .sort(([, a], [, b]) => b - a)
      .slice(0, 20); // Consider top 20 combinations

    for (const [fieldCombination, frequency] of sortedCombinations) {
      const fields = fieldCombination.split(',');

      // Apply ESR (Equality, Sort, Range) pattern optimization
      const optimizedIndex = this.optimizeIndexWithESRPattern(fields, analysis);

      if (optimizedIndex && this.validateIndexUtility(optimizedIndex, analysis)) {
        compoundIndexes.push({
          type: 'compound',
          name: `idx_${optimizedIndex.fields.map(f => f.field).join('_')}`,
          specification: this.buildIndexSpecification(optimizedIndex.fields),
          options: optimizedIndex.options,
          reasoning: optimizedIndex.reasoning,
          estimatedImpact: this.estimateIndexImpact(optimizedIndex, analysis),
          queryPatterns: this.identifyMatchingQueries(optimizedIndex, analysis),
          priority: this.calculateIndexPriority(optimizedIndex, frequency, analysis)
        });
      }
    }

    // Sort by priority and return top recommendations
    return compoundIndexes
      .sort((a, b) => b.priority - a.priority)
      .slice(0, this.performanceTargets.maxIndexesPerCollection);
  }

  optimizeIndexWithESRPattern(fields, analysis) {
    console.log(`Optimizing index for fields: ${fields.join(', ')} using ESR pattern...`);

    const optimizedFields = [];
    const fieldAnalysis = new Map();

    // Analyze each field's characteristics
    fields.forEach(field => {
      const filterTypes = analysis.filterTypes.get(field) || new Set();
      const usage = analysis.fieldUsage.get(field) || 0;
      const selectivity = analysis.selectivityEstimates.get(field) || 0.5;

      fieldAnalysis.set(field, {
        filterTypes: Array.from(filterTypes),
        usage: usage,
        selectivity: selectivity,
        isEquality: filterTypes.has('equality') || filterTypes.has('selective_in'),
        isRange: filterTypes.has('range'),
        isSort: this.isFieldUsedInSort(field, analysis),
        sortDirection: this.getSortDirection(field, analysis)
      });
    });

    // Step 1: Equality fields first (highest selectivity first)
    const equalityFields = fields
      .filter(field => fieldAnalysis.get(field).isEquality)
      .sort((a, b) => fieldAnalysis.get(b).selectivity - fieldAnalysis.get(a).selectivity);

    equalityFields.forEach(field => {
      const fieldInfo = fieldAnalysis.get(field);
      optimizedFields.push({
        field: field,
        direction: 1,
        type: 'equality',
        selectivity: fieldInfo.selectivity,
        reasoning: `Equality filter with ${(fieldInfo.selectivity * 100).toFixed(1)}% selectivity`
      });
    });

    // Step 2: Sort fields (maintaining sort direction)
    const sortFields = fields
      .filter(field => fieldAnalysis.get(field).isSort && !fieldAnalysis.get(field).isEquality)
      .sort((a, b) => fieldAnalysis.get(b).usage - fieldAnalysis.get(a).usage);

    sortFields.forEach(field => {
      const fieldInfo = fieldAnalysis.get(field);
      optimizedFields.push({
        field: field,
        direction: fieldInfo.sortDirection || 1,
        type: 'sort',
        selectivity: fieldInfo.selectivity,
        reasoning: `Sort field with ${fieldInfo.usage} usage frequency`
      });
    });

    // Step 3: Range fields last (lowest selectivity impact)
    const rangeFields = fields
      .filter(field => fieldAnalysis.get(field).isRange && 
                      !fieldAnalysis.get(field).isEquality && 
                      !fieldAnalysis.get(field).isSort)
      .sort((a, b) => fieldAnalysis.get(b).selectivity - fieldAnalysis.get(a).selectivity);

    rangeFields.forEach(field => {
      const fieldInfo = fieldAnalysis.get(field);
      optimizedFields.push({
        field: field,
        direction: 1,
        type: 'range',
        selectivity: fieldInfo.selectivity,
        reasoning: `Range filter with ${(fieldInfo.selectivity * 100).toFixed(1)}% selectivity`
      });
    });

    // Validate and return optimized index
    if (optimizedFields.length === 0) return null;

    return {
      fields: optimizedFields,
      options: this.generateIndexOptions(optimizedFields, analysis),
      reasoning: `ESR-optimized compound index: ${optimizedFields.length} fields arranged for optimal query performance`,
      estimatedSelectivity: this.calculateCompoundSelectivity(optimizedFields),
      supportedQueryTypes: this.identifySupportedQueryTypes(optimizedFields, analysis)
    };
  }

  async generatePartialIndexes(analysis) {
    console.log('Generating partial index recommendations for selective filtering...');

    const partialIndexes = [];

    // Identify fields with high selectivity potential
    const selectiveFields = Array.from(analysis.selectivityEstimates.entries())
      .filter(([field, selectivity]) => selectivity < this.performanceTargets.minIndexSelectivity)
      .sort(([, a], [, b]) => a - b); // Lower selectivity first (more selective)

    for (const [field, selectivity] of selectiveFields) {
      const filterTypes = analysis.filterTypes.get(field) || new Set();
      const usage = analysis.fieldUsage.get(field) || 0;

      // Generate partial filter conditions
      const partialFilters = this.generatePartialFilterConditions(field, filterTypes, analysis);

      for (const partialFilter of partialFilters) {
        const partialIndex = {
          type: 'partial',
          name: `idx_${field}_${partialFilter.suffix}`,
          specification: { [field]: 1 },
          options: {
            partialFilterExpression: partialFilter.expression,
            background: true
          },
          reasoning: partialFilter.reasoning,
          estimatedReduction: partialFilter.estimatedReduction,
          applicableQueries: partialFilter.applicableQueries,
          priority: this.calculatePartialIndexPriority(field, usage, selectivity, partialFilter)
        };

        if (this.validatePartialIndexUtility(partialIndex, analysis)) {
          partialIndexes.push(partialIndex);
        }
      }
    }

    return partialIndexes
      .sort((a, b) => b.priority - a.priority)
      .slice(0, Math.floor(this.performanceTargets.maxIndexesPerCollection / 3));
  }

  generatePartialFilterConditions(field, filterTypes, analysis) {
    const partialFilters = [];

    // Status/category fields with selective values
    if (filterTypes.has('equality') || filterTypes.has('selective_in')) {
      partialFilters.push({
        expression: { [field]: { $in: ['active', 'premium', 'verified'] } },
        suffix: 'active_premium',
        reasoning: `Partial index for high-value ${field} categories`,
        estimatedReduction: 0.7,
        applicableQueries: [`${field} equality matches for active/premium users`]
      });
    }

    // Date fields with recency focus
    if (filterTypes.has('range') && field.includes('date') || field.includes('time')) {
      partialFilters.push({
        expression: { [field]: { $gte: new Date(Date.now() - 90 * 24 * 60 * 60 * 1000) } },
        suffix: 'recent_90d',
        reasoning: `Partial index for recent ${field} within 90 days`,
        estimatedReduction: 0.8,
        applicableQueries: [`Recent ${field} range queries`]
      });
    }

    // Numeric fields with value thresholds
    if (filterTypes.has('range') && (field.includes('amount') || field.includes('count') || field.includes('score'))) {
      partialFilters.push({
        expression: { [field]: { $gt: 0 } },
        suffix: 'positive_values',
        reasoning: `Partial index excluding zero/null ${field} values`,
        estimatedReduction: 0.6,
        applicableQueries: [`${field} range queries for positive values`]
      });
    }

    return partialFilters;
  }

  async generateCoveringIndexes(analysis) {
    console.log('Generating covering index recommendations for query optimization...');

    const coveringIndexes = [];

    // Analyze projection patterns to identify covering index opportunities
    const projectionAnalysis = Array.from(analysis.projectionPatterns.entries())
      .sort(([, a], [, b]) => b - a)
      .slice(0, 10); // Top 10 projection patterns

    for (const [projectionKey, frequency] of projectionAnalysis) {
      const projectedFields = projectionKey.split(',');

      // Find queries that could benefit from covering indexes
      const candidateQueries = this.identifyConveringIndexCandidates(projectedFields, analysis);

      if (candidateQueries.length > 0) {
        const coveringIndex = this.designCoveringIndex(projectedFields, candidateQueries, analysis);

        if (coveringIndex && this.validateCoveringIndexBenefit(coveringIndex, analysis)) {
          coveringIndexes.push({
            type: 'covering',
            name: `idx_covering_${coveringIndex.keyFields.join('_')}`,
            specification: coveringIndex.specification,
            options: coveringIndex.options,
            reasoning: coveringIndex.reasoning,
            coveredQueries: candidateQueries.length,
            projectedFields: projectedFields,
            estimatedImpact: this.estimateCoveringIndexImpact(coveringIndex, frequency),
            priority: this.calculateCoveringIndexPriority(coveringIndex, frequency, candidateQueries.length)
          });
        }
      }
    }

    return coveringIndexes
      .sort((a, b) => b.priority - a.priority)
      .slice(0, Math.floor(this.performanceTargets.maxIndexesPerCollection / 4));
  }

  designCoveringIndex(projectedFields, candidateQueries, analysis) {
    // Analyze filter and sort patterns from candidate queries
    const filterFields = new Set();
    const sortFields = new Map();

    candidateQueries.forEach(query => {
      Object.keys(query.filter || {}).forEach(field => {
        if (!field.startsWith('$')) {
          filterFields.add(field);
        }
      });

      Object.entries(query.sort || {}).forEach(([field, direction]) => {
        sortFields.set(field, direction);
      });
    });

    // Design optimal key structure
    const keyFields = [];
    const includeFields = [];

    // Add filter fields to key (equality first, then range)
    const equalityFields = Array.from(filterFields).filter(field => {
      const filterTypes = analysis.filterTypes.get(field) || new Set();
      return filterTypes.has('equality') || filterTypes.has('selective_in');
    });

    const rangeFields = Array.from(filterFields).filter(field => {
      const filterTypes = analysis.filterTypes.get(field) || new Set();
      return filterTypes.has('range');
    });

    // Add equality fields to key
    equalityFields.forEach(field => {
      keyFields.push(field);
    });

    // Add sort fields to key
    sortFields.forEach((direction, field) => {
      if (!keyFields.includes(field)) {
        keyFields.push(field);
      }
    });

    // Add range fields to key
    rangeFields.forEach(field => {
      if (!keyFields.includes(field)) {
        keyFields.push(field);
      }
    });

    // Add remaining projected fields as included fields
    projectedFields.forEach(field => {
      if (!keyFields.includes(field)) {
        includeFields.push(field);
      }
    });

    if (keyFields.length === 0) return null;

    // Build index specification
    const specification = {};
    keyFields.forEach(field => {
      const direction = sortFields.get(field) || 1;
      specification[field] = direction;
    });

    return {
      keyFields: keyFields,
      includeFields: includeFields,
      specification: specification,
      options: {
        background: true,
        // Include non-key fields for covering capability
        ...(includeFields.length > 0 && { includeFields: includeFields })
      },
      reasoning: `Covering index with ${keyFields.length} key fields and ${includeFields.length} included fields`,
      estimatedCoverage: this.calculateQueryCoverage(keyFields, includeFields, candidateQueries)
    };
  }

  async generateSpecializedIndexes(analysis) {
    console.log('Generating specialized index recommendations...');

    const specializedIndexes = [];

    // Text search indexes for string fields with pattern matching
    const textFields = this.identifyTextSearchFields(analysis);
    textFields.forEach(textField => {
      specializedIndexes.push({
        type: 'text',
        name: `idx_text_${textField.field}`,
        specification: { [textField.field]: 'text' },
        options: {
          background: true,
          default_language: 'english',
          weights: { [textField.field]: textField.weight }
        },
        reasoning: `Text search index for ${textField.field} pattern matching`,
        applicableQueries: textField.queries,
        priority: textField.priority
      });
    });

    // Geospatial indexes for location data
    const geoFields = this.identifyGeospatialFields(analysis);
    geoFields.forEach(geoField => {
      specializedIndexes.push({
        type: 'geospatial',
        name: `idx_geo_${geoField.field}`,
        specification: { [geoField.field]: '2dsphere' },
        options: {
          background: true,
          '2dsphereIndexVersion': 3
        },
        reasoning: `Geospatial index for ${geoField.field} location queries`,
        applicableQueries: geoField.queries,
        priority: geoField.priority
      });
    });

    // TTL indexes for time-based data expiration
    const ttlFields = this.identifyTTLFields(analysis);
    ttlFields.forEach(ttlField => {
      specializedIndexes.push({
        type: 'ttl',
        name: `idx_ttl_${ttlField.field}`,
        specification: { [ttlField.field]: 1 },
        options: {
          background: true,
          expireAfterSeconds: ttlField.expireAfterSeconds
        },
        reasoning: `TTL index for automatic ${ttlField.field} data expiration`,
        expirationPeriod: ttlField.expirationPeriod,
        priority: ttlField.priority
      });
    });

    // Sparse indexes for fields with many null values
    const sparseFields = this.identifySparseFields(analysis);
    sparseFields.forEach(sparseField => {
      specializedIndexes.push({
        type: 'sparse',
        name: `idx_sparse_${sparseField.field}`,
        specification: { [sparseField.field]: 1 },
        options: {
          background: true,
          sparse: true
        },
        reasoning: `Sparse index for ${sparseField.field} excluding null values`,
        nullPercentage: sparseField.nullPercentage,
        priority: sparseField.priority
      });
    });

    return specializedIndexes
      .sort((a, b) => b.priority - a.priority)
      .slice(0, Math.floor(this.performanceTargets.maxIndexesPerCollection / 2));
  }

  async executeIndexingPlan(collection, plan) {
    console.log(`Executing indexing plan for ${collection.collectionName}...`);

    const results = {
      successful: [],
      failed: [],
      skipped: [],
      totalTime: 0
    };

    const startTime = Date.now();

    for (const index of plan.recommendedIndexes) {
      try {
        console.log(`Creating index: ${index.name}`);

        // Check if index already exists
        const existingIndexes = await collection.listIndexes().toArray();
        const indexExists = existingIndexes.some(existing => existing.name === index.name);

        if (indexExists) {
          console.log(`Index ${index.name} already exists, skipping...`);
          results.skipped.push({
            name: index.name,
            reason: 'Index already exists'
          });
          continue;
        }

        // Create the index
        const indexStartTime = Date.now();
        await collection.createIndex(index.specification, {
          name: index.name,
          ...index.options
        });
        const indexCreationTime = Date.now() - indexStartTime;

        results.successful.push({
          name: index.name,
          type: index.type,
          specification: index.specification,
          creationTime: indexCreationTime,
          estimatedImpact: index.estimatedImpact
        });

        console.log(`Index ${index.name} created successfully in ${indexCreationTime}ms`);

      } catch (error) {
        console.error(`Failed to create index ${index.name}:`, error.message);
        results.failed.push({
          name: index.name,
          type: index.type,
          error: error.message,
          specification: index.specification
        });
      }
    }

    results.totalTime = Date.now() - startTime;

    console.log(`Index creation completed in ${results.totalTime}ms`);
    console.log(`Successful: ${results.successful.length}, Failed: ${results.failed.length}, Skipped: ${results.skipped.length}`);

    return results;
  }

  async validateIndexPerformance(collection, plan, queryPatterns) {
    console.log('Validating index performance with test queries...');

    const validation = {
      queries: [],
      summary: {
        totalQueries: queryPatterns.length,
        improvedQueries: 0,
        avgImprovementPct: 0,
        significantImprovements: 0
      }
    };

    for (const pattern of queryPatterns.slice(0, 20)) { // Test top 20 patterns
      try {
        // Execute query with explain to get performance metrics
        const collection_handle = this.collections[collection.collectionName] || collection;

        let cursor;
        if (pattern.aggregation) {
          cursor = collection_handle.aggregate(pattern.aggregation);
        } else {
          cursor = collection_handle.find(pattern.filter || {});
          if (pattern.sort) cursor.sort(pattern.sort);
          if (pattern.limit) cursor.limit(pattern.limit);
          if (pattern.projection) cursor.project(pattern.projection);
        }

        const explainResult = await cursor.explain('executionStats');

        const queryValidation = {
          pattern: pattern.name || 'Unnamed query',
          executionTimeMs: explainResult.executionStats?.executionTimeMillis || 0,
          totalDocsExamined: explainResult.executionStats?.totalDocsExamined || 0,
          totalDocsReturned: explainResult.executionStats?.totalDocsReturned || 0,
          indexesUsed: this.extractIndexNames(explainResult),
          efficiency: this.calculateQueryEfficiency(explainResult),
          grade: this.assignPerformanceGrade(explainResult),
          improvement: this.calculateImprovement(pattern, explainResult)
        };

        validation.queries.push(queryValidation);

        if (queryValidation.improvement > 0) {
          validation.summary.improvedQueries++;
          validation.summary.avgImprovementPct += queryValidation.improvement;
        }

        if (queryValidation.improvement > 50) {
          validation.summary.significantImprovements++;
        }

      } catch (error) {
        console.warn(`Query validation failed for pattern: ${pattern.name}`, error.message);
        validation.queries.push({
          pattern: pattern.name || 'Unnamed query',
          error: error.message,
          success: false
        });
      }
    }

    if (validation.summary.improvedQueries > 0) {
      validation.summary.avgImprovementPct /= validation.summary.improvedQueries;
    }

    console.log(`Performance validation completed: ${validation.summary.improvedQueries}/${validation.summary.totalQueries} queries improved`);
    console.log(`Average improvement: ${validation.summary.avgImprovementPct.toFixed(1)}%`);
    console.log(`Significant improvements: ${validation.summary.significantImprovements}`);

    return validation;
  }

  // Helper methods for advanced index analysis and optimization

  buildIndexSpecification(fields) {
    const spec = {};
    fields.forEach(field => {
      spec[field.field] = field.direction;
    });
    return spec;
  }

  generateIndexOptions(fields, analysis) {
    return {
      background: true,
      ...(this.shouldUsePartialFilter(fields, analysis) && {
        partialFilterExpression: this.buildOptimalPartialFilter(fields, analysis)
      })
    };
  }

  isFieldUsedInSort(field, analysis) {
    for (const [sortPattern] of analysis.sortPatterns) {
      if (sortPattern.includes(`${field}:`)) {
        return true;
      }
    }
    return false;
  }

  getSortDirection(field, analysis) {
    for (const [sortPattern] of analysis.sortPatterns) {
      const fieldPattern = sortPattern.split(',').find(pattern => pattern.startsWith(`${field}:`));
      if (fieldPattern) {
        return parseInt(fieldPattern.split(':')[1]) || 1;
      }
    }
    return 1;
  }

  calculateCompoundSelectivity(fields) {
    // Estimate compound selectivity using field independence assumption
    return fields.reduce((selectivity, field) => {
      return selectivity * (field.selectivity || 0.1);
    }, 1);
  }

  validateIndexUtility(index, analysis) {
    // Validate that index provides meaningful benefit
    const estimatedSelectivity = this.calculateCompoundSelectivity(index.fields);
    const supportedQueries = this.identifyMatchingQueries(index, analysis);

    return estimatedSelectivity < 0.5 && supportedQueries.length > 0;
  }

  identifyMatchingQueries(index, analysis) {
    // Simplified query matching logic
    const matchingQueries = [];
    const indexFields = new Set(index.fields.map(f => f.field));

    // Check field combinations that would benefit from this index
    for (const [fieldCombination, frequency] of analysis.fieldCombinations) {
      const queryFields = new Set(fieldCombination.split(','));
      const overlap = [...indexFields].filter(field => queryFields.has(field));

      if (overlap.length >= 2) { // At least 2 fields overlap
        matchingQueries.push({
          fields: fieldCombination,
          frequency: frequency,
          coverage: overlap.length / indexFields.size
        });
      }
    }

    return matchingQueries;
  }

  calculateIndexPriority(index, frequency, analysis) {
    const baseScore = frequency * 10;
    const selectivityBonus = (1 - index.estimatedSelectivity) * 50;
    const fieldCountPenalty = index.fields.length * 5;

    return Math.max(0, baseScore + selectivityBonus - fieldCountPenalty);
  }

  calculatePerformanceImprovement(plan) {
    // Simplified improvement estimation
    const baseImprovement = plan.recommendedIndexes.length * 15; // 15% per index
    const compoundBonus = plan.recommendedIndexes.filter(idx => idx.type === 'compound').length * 25;
    const partialBonus = plan.recommendedIndexes.filter(idx => idx.type === 'partial').length * 35;

    return Math.min(90, baseImprovement + compoundBonus + partialBonus);
  }

  extractIndexNames(explainResult) {
    const indexes = new Set();

    const extractFromStage = (stage) => {
      if (stage.indexName) {
        indexes.add(stage.indexName);
      }
      if (stage.inputStage) {
        extractFromStage(stage.inputStage);
      }
      if (stage.inputStages) {
        stage.inputStages.forEach(extractFromStage);
      }
    };

    if (explainResult.executionStats?.executionStages) {
      extractFromStage(explainResult.executionStats.executionStages);
    }

    return Array.from(indexes);
  }

  calculateQueryEfficiency(explainResult) {
    const stats = explainResult.executionStats;
    if (!stats) return 0;

    const examined = stats.totalDocsExamined || 0;
    const returned = stats.totalDocsReturned || 0;

    return examined > 0 ? returned / examined : 1;
  }

  assignPerformanceGrade(explainResult) {
    const efficiency = this.calculateQueryEfficiency(explainResult);
    const executionTime = explainResult.executionStats?.executionTimeMillis || 0;
    const hasIndexScan = this.extractIndexNames(explainResult).length > 0;

    let score = 0;

    // Efficiency scoring
    if (efficiency >= 0.8) score += 40;
    else if (efficiency >= 0.5) score += 30;
    else if (efficiency >= 0.2) score += 20;
    else if (efficiency >= 0.1) score += 10;

    // Execution time scoring
    if (executionTime <= 50) score += 35;
    else if (executionTime <= 100) score += 25;
    else if (executionTime <= 250) score += 15;
    else if (executionTime <= 500) score += 5;

    // Index usage scoring
    if (hasIndexScan) score += 25;

    if (score >= 85) return 'A';
    else if (score >= 70) return 'B';
    else if (score >= 50) return 'C';
    else if (score >= 30) return 'D';
    else return 'F';
  }

  calculateImprovement(pattern, explainResult) {
    // Simplified improvement calculation
    const efficiency = this.calculateQueryEfficiency(explainResult);
    const executionTime = explainResult.executionStats?.executionTimeMillis || 0;
    const hasIndexScan = this.extractIndexNames(explainResult).length > 0;

    let improvementScore = 0;

    if (hasIndexScan) improvementScore += 30;
    if (efficiency > 0.5) improvementScore += 40;
    if (executionTime < 100) improvementScore += 30;

    return Math.min(100, improvementScore);
  }

  // Additional helper methods for specialized index types

  identifyTextSearchFields(analysis) {
    const textFields = [];

    analysis.filterTypes.forEach((types, field) => {
      if (types.has('pattern_match') && 
          (field.includes('name') || field.includes('title') || field.includes('description'))) {
        textFields.push({
          field: field,
          weight: analysis.fieldUsage.get(field) || 1,
          queries: [`Text search on ${field}`],
          priority: (analysis.fieldUsage.get(field) || 0) * 10
        });
      }
    });

    return textFields;
  }

  identifyGeospatialFields(analysis) {
    const geoFields = [];

    analysis.fieldUsage.forEach((usage, field) => {
      if (field.includes('location') || field.includes('coordinates') || 
          field.includes('lat') || field.includes('lng') || field.includes('geo')) {
        geoFields.push({
          field: field,
          queries: [`Geospatial queries on ${field}`],
          priority: usage * 15
        });
      }
    });

    return geoFields;
  }

  identifyTTLFields(analysis) {
    const ttlFields = [];

    analysis.fieldUsage.forEach((usage, field) => {
      if (field.includes('expires') || field.includes('expire') || 
          field === 'createdAt' || field === 'updatedAt') {
        ttlFields.push({
          field: field,
          expireAfterSeconds: this.getExpireAfterSeconds(field),
          expirationPeriod: this.getExpirationPeriod(field),
          priority: usage * 5
        });
      }
    });

    return ttlFields;
  }

  identifySparseFields(analysis) {
    const sparseFields = [];

    // Fields that are likely to have many null values
    const potentialSparseFields = ['phone', 'middle_name', 'company', 'notes', 'optional_field'];

    analysis.fieldUsage.forEach((usage, field) => {
      if (potentialSparseFields.some(sparse => field.includes(sparse))) {
        sparseFields.push({
          field: field,
          nullPercentage: 0.6, // Estimated
          priority: usage * 8
        });
      }
    });

    return sparseFields;
  }

  getExpireAfterSeconds(field) {
    const expirationMap = {
      'session': 86400,        // 1 day
      'temp': 3600,           // 1 hour  
      'cache': 1800,          // 30 minutes
      'token': 3600,          // 1 hour
      'verification': 86400,   // 1 day
      'expires': 0            // Use field value
    };

    for (const [key, seconds] of Object.entries(expirationMap)) {
      if (field.includes(key)) {
        return seconds;
      }
    }

    return 86400; // Default 1 day
  }

  getExpirationPeriod(field) {
    const expireAfter = this.getExpireAfterSeconds(field);
    if (expireAfter >= 86400) return `${Math.floor(expireAfter / 86400)} days`;
    if (expireAfter >= 3600) return `${Math.floor(expireAfter / 3600)} hours`;
    return `${Math.floor(expireAfter / 60)} minutes`;
  }

  async estimateFieldSelectivity(analysis) {
    // Simplified selectivity estimation
    // In production, this would use actual data sampling

    analysis.fieldUsage.forEach((usage, field) => {
      let estimatedSelectivity = 0.5; // Default

      // Status/enum fields typically have low cardinality
      if (field.includes('status') || field.includes('type') || field.includes('category')) {
        estimatedSelectivity = 0.1;
      }
      // ID fields have high cardinality
      else if (field.includes('id') || field.includes('_id')) {
        estimatedSelectivity = 0.9;
      }
      // Email fields have high cardinality
      else if (field.includes('email')) {
        estimatedSelectivity = 0.8;
      }
      // Date fields vary based on range
      else if (field.includes('date') || field.includes('time')) {
        estimatedSelectivity = 0.3;
      }

      analysis.selectivityEstimates.set(field, estimatedSelectivity);
    });
  }

  identifyOptimalFieldCombinations(analysis) {
    const combinations = [];

    // Sort combinations by frequency and expected performance impact
    const sortedCombinations = Array.from(analysis.fieldCombinations.entries())
      .sort(([, a], [, b]) => b - a);

    sortedCombinations.forEach(([combination, frequency]) => {
      const fields = combination.split(',');
      const totalSelectivity = fields.reduce((product, field) => {
        return product * (analysis.selectivityEstimates.get(field) || 0.5);
      }, 1);

      combinations.push({
        fields: fields,
        frequency: frequency,
        selectivity: totalSelectivity,
        score: frequency * (1 - totalSelectivity) * 100,
        reasoning: `Combination of ${fields.length} fields with ${frequency} usage frequency`
      });
    });

    return combinations
      .sort((a, b) => b.score - a.score)
      .slice(0, 15);
  }

  generateIndexingRecommendations(analysis, optimalCombinations) {
    return {
      topFieldCombinations: optimalCombinations.slice(0, 5),
      highUsageFields: Array.from(analysis.fieldUsage.entries())
        .sort(([, a], [, b]) => b - a)
        .slice(0, 10)
        .map(([field, usage]) => ({ field, usage })),
      selectiveFields: Array.from(analysis.selectivityEstimates.entries())
        .filter(([, selectivity]) => selectivity < 0.2)
        .sort(([, a], [, b]) => a - b)
        .map(([field, selectivity]) => ({ field, selectivity })),
      commonSortPatterns: Array.from(analysis.sortPatterns.entries())
        .sort(([, a], [, b]) => b - a)
        .slice(0, 5)
        .map(([pattern, frequency]) => ({ pattern, frequency }))
    };
  }
}

// Benefits of MongoDB Advanced Indexing Strategies:
// - Comprehensive compound index design using ESR (Equality, Sort, Range) optimization patterns
// - Intelligent partial indexing for selective filtering and reduced storage overhead
// - Sophisticated covering index generation for complete query optimization
// - Specialized index support for text search, geospatial, TTL, and sparse data patterns
// - Automated index performance validation and impact measurement
// - Production-ready index creation with background processing and error handling
// - Advanced query pattern analysis and field combination optimization
// - Integration with MongoDB's native indexing capabilities and query optimizer
// - Comprehensive performance monitoring and index effectiveness tracking
// - SQL-compatible index management through QueryLeaf integration

module.exports = {
  MongoIndexOptimizer
};

Understanding MongoDB Compound Index Architecture

Advanced Index Design Patterns and Performance Optimization

Implement sophisticated compound indexing strategies for production-scale applications:

// Production-ready compound index management and optimization patterns
class ProductionIndexManager extends MongoIndexOptimizer {
  constructor(db) {
    super(db);

    this.productionConfig = {
      maxConcurrentIndexBuilds: 2,
      indexMaintenanceWindows: ['02:00-04:00'],
      performanceMonitoringInterval: 300000, // 5 minutes
      autoOptimizationEnabled: true,
      indexUsageTrackingPeriod: 86400000 // 24 hours
    };

    this.indexMetrics = new Map();
    this.optimizationQueue = [];
  }

  async implementProductionIndexingWorkflow(collections) {
    console.log('Implementing production-grade indexing workflow...');

    const workflow = {
      phase1_analysis: await this.performComprehensiveIndexAnalysis(collections),
      phase2_planning: await this.generateProductionIndexPlan(collections),
      phase3_execution: await this.executeProductionIndexPlan(collections),
      phase4_monitoring: await this.setupIndexPerformanceMonitoring(collections),
      phase5_optimization: await this.implementContinuousOptimization(collections)
    };

    return {
      workflow: workflow,
      summary: this.generateWorkflowSummary(workflow),
      monitoring: await this.setupProductionMonitoring(collections),
      maintenance: await this.scheduleIndexMaintenance(collections)
    };
  }

  async performComprehensiveIndexAnalysis(collections) {
    console.log('Performing comprehensive production index analysis...');

    const analysis = {
      collections: [],
      globalPatterns: new Map(),
      crossCollectionOptimizations: [],
      resourceImpact: {},
      riskAssessment: {}
    };

    for (const collectionName of collections) {
      const collection = this.collections[collectionName];

      // Analyze current index usage
      const indexStats = await this.analyzeCurrentIndexUsage(collection);

      // Sample query patterns from profiler
      const queryPatterns = await this.extractQueryPatternsFromProfiler(collection);

      // Analyze data distribution and selectivity
      const dataDistribution = await this.analyzeDataDistribution(collection);

      // Resource utilization analysis
      const resourceUsage = await this.analyzeIndexResourceUsage(collection);

      analysis.collections.push({
        name: collectionName,
        indexStats: indexStats,
        queryPatterns: queryPatterns,
        dataDistribution: dataDistribution,
        resourceUsage: resourceUsage,
        recommendations: await this.generateCollectionSpecificRecommendations(collection, queryPatterns, dataDistribution)
      });
    }

    // Identify global optimization opportunities
    analysis.crossCollectionOptimizations = await this.identifyCrossCollectionOptimizations(analysis.collections);

    // Assess resource impact and risks
    analysis.resourceImpact = this.assessResourceImpact(analysis.collections);
    analysis.riskAssessment = this.performIndexingRiskAssessment(analysis.collections);

    return analysis;
  }

  async analyzeCurrentIndexUsage(collection) {
    console.log(`Analyzing current index usage for ${collection.collectionName}...`);

    try {
      // Get index statistics
      const indexStats = await collection.aggregate([
        { $indexStats: {} }
      ]).toArray();

      // Get collection statistics
      const collStats = await this.db.runCommand({ collStats: collection.collectionName });

      const analysis = {
        indexes: [],
        totalIndexSize: 0,
        unusedIndexes: [],
        underutilizedIndexes: [],
        highImpactIndexes: [],
        recommendations: []
      };

      indexStats.forEach(indexStat => {
        const indexAnalysis = {
          name: indexStat.name,
          key: indexStat.key,
          accessCount: indexStat.accesses?.ops || 0,
          accessSinceLastRestart: indexStat.accesses?.since || new Date(),
          sizeBytes: indexStat.size || 0,

          // Calculate utilization metrics
          utilizationScore: this.calculateIndexUtilizationScore(indexStat),
          efficiency: this.calculateIndexEfficiency(indexStat, collStats),

          // Categorize index usage
          category: this.categorizeIndexUsage(indexStat),

          // Performance impact assessment
          impactScore: this.calculateIndexImpactScore(indexStat, collStats)
        };

        analysis.indexes.push(indexAnalysis);
        analysis.totalIndexSize += indexAnalysis.sizeBytes;

        // Categorize indexes based on usage patterns
        if (indexAnalysis.category === 'unused') {
          analysis.unusedIndexes.push(indexAnalysis);
        } else if (indexAnalysis.category === 'underutilized') {
          analysis.underutilizedIndexes.push(indexAnalysis);
        } else if (indexAnalysis.impactScore > 80) {
          analysis.highImpactIndexes.push(indexAnalysis);
        }
      });

      // Generate optimization recommendations
      analysis.recommendations = this.generateIndexOptimizationRecommendations(analysis);

      return analysis;

    } catch (error) {
      console.warn(`Failed to analyze index usage for ${collection.collectionName}:`, error.message);
      return { error: error.message };
    }
  }

  async extractQueryPatternsFromProfiler(collection) {
    console.log(`Extracting query patterns from profiler for ${collection.collectionName}...`);

    try {
      // Query the profiler collection for recent operations
      const profileData = await this.db.collection('system.profile').aggregate([
        {
          $match: {
            ns: `${this.db.databaseName}.${collection.collectionName}`,
            ts: { $gte: new Date(Date.now() - this.productionConfig.indexUsageTrackingPeriod) },
            'command.find': { $exists: true }
          }
        },
        {
          $group: {
            _id: {
              filter: '$command.filter',
              sort: '$command.sort',
              projection: '$command.projection'
            },
            count: { $sum: 1 },
            avgExecutionTime: { $avg: '$millis' },
            totalDocsExamined: { $sum: '$docsExamined' },
            totalDocsReturned: { $sum: '$nreturned' },
            indexesUsed: { $addToSet: '$planSummary' }
          }
        },
        {
          $sort: { count: -1 }
        },
        {
          $limit: 100
        }
      ]).toArray();

      const patterns = profileData.map(pattern => ({
        filter: pattern._id.filter || {},
        sort: pattern._id.sort || {},
        projection: pattern._id.projection || {},
        frequency: pattern.count,
        avgExecutionTime: pattern.avgExecutionTime,
        efficiency: pattern.totalDocsReturned / Math.max(pattern.totalDocsExamined, 1),
        indexesUsed: pattern.indexesUsed,
        priority: this.calculateQueryPatternPriority(pattern)
      }));

      return patterns.sort((a, b) => b.priority - a.priority);

    } catch (error) {
      console.warn(`Failed to extract query patterns for ${collection.collectionName}:`, error.message);
      return [];
    }
  }

  async implementAdvancedIndexMonitoring(collections) {
    console.log('Setting up advanced index performance monitoring...');

    const monitoringConfig = {
      collections: collections,
      metrics: {
        indexUtilization: true,
        queryPerformance: true,
        resourceConsumption: true,
        growthTrends: true
      },
      alerts: {
        unusedIndexes: { threshold: 0.01, period: '7d' },
        slowQueries: { threshold: 1000, period: '1h' },
        highResourceUsage: { threshold: 0.8, period: '15m' }
      },
      reporting: {
        frequency: 'daily',
        recipients: ['[email protected]']
      }
    };

    // Create monitoring aggregation pipelines
    const monitoringPipelines = await this.createMonitoringPipelines(collections);

    // Setup automated alerts
    const alertSystem = await this.setupIndexAlertSystem(monitoringConfig);

    // Initialize performance tracking
    const performanceTracker = await this.initializePerformanceTracking(collections);

    return {
      config: monitoringConfig,
      pipelines: monitoringPipelines,
      alerts: alertSystem,
      tracking: performanceTracker,
      dashboard: await this.createIndexMonitoringDashboard(collections)
    };
  }

  calculateIndexUtilizationScore(indexStat) {
    const accessCount = indexStat.accesses?.ops || 0;
    const timeSinceLastRestart = Date.now() - (indexStat.accesses?.since?.getTime() || Date.now());
    const hoursRunning = timeSinceLastRestart / (1000 * 60 * 60);

    // Calculate accesses per hour
    const accessesPerHour = hoursRunning > 0 ? accessCount / hoursRunning : 0;

    // Score based on usage frequency
    if (accessesPerHour > 100) return 100;
    else if (accessesPerHour > 10) return 80;
    else if (accessesPerHour > 1) return 60;
    else if (accessesPerHour > 0.1) return 40;
    else if (accessesPerHour > 0) return 20;
    else return 0;
  }

  calculateIndexEfficiency(indexStat, collStats) {
    const indexSize = indexStat.size || 0;
    const accessCount = indexStat.accesses?.ops || 0;
    const totalCollectionSize = collStats.size || 1;

    // Efficiency based on size-to-usage ratio
    const sizeRatio = indexSize / totalCollectionSize;
    const usageEfficiency = accessCount > 0 ? Math.min(100, accessCount / sizeRatio) : 0;

    return Math.round(usageEfficiency);
  }

  categorizeIndexUsage(indexStat) {
    const utilizationScore = this.calculateIndexUtilizationScore(indexStat);

    if (utilizationScore === 0) return 'unused';
    else if (utilizationScore < 20) return 'underutilized';
    else if (utilizationScore < 60) return 'moderate';
    else if (utilizationScore < 90) return 'well_used';
    else return 'critical';
  }

  calculateIndexImpactScore(indexStat, collStats) {
    const utilizationScore = this.calculateIndexUtilizationScore(indexStat);
    const efficiency = this.calculateIndexEfficiency(indexStat, collStats);
    const sizeImpact = (indexStat.size || 0) / (collStats.size || 1) * 100;

    // Combined impact score
    return Math.round((utilizationScore * 0.5) + (efficiency * 0.3) + (sizeImpact * 0.2));
  }

  calculateQueryPatternPriority(pattern) {
    const frequencyScore = Math.min(100, pattern.count * 2);
    const performanceScore = pattern.avgExecutionTime > 100 ? 50 : 
                           pattern.avgExecutionTime > 50 ? 30 : 10;
    const efficiencyScore = pattern.efficiency > 0.8 ? 0 : 
                          pattern.efficiency > 0.5 ? 20 : 40;

    return frequencyScore + performanceScore + efficiencyScore;
  }

  generateIndexOptimizationRecommendations(analysis) {
    const recommendations = [];

    // Unused index recommendations
    analysis.unusedIndexes.forEach(index => {
      if (index.name !== '_id_') { // Never recommend removing _id_ index
        recommendations.push({
          type: 'DROP_INDEX',
          priority: 'LOW',
          index: index.name,
          reason: `Index has ${index.accessCount} accesses since last restart`,
          estimatedSavings: `${(index.sizeBytes / 1024 / 1024).toFixed(2)}MB storage`,
          risk: 'Low - unused index can be safely removed'
        });
      }
    });

    // Underutilized index recommendations
    analysis.underutilizedIndexes.forEach(index => {
      recommendations.push({
        type: 'REVIEW_INDEX',
        priority: 'MEDIUM',
        index: index.name,
        reason: `Low utilization score: ${index.utilizationScore}`,
        suggestion: 'Review query patterns to determine if index can be optimized or removed',
        risk: 'Medium - verify index necessity before removal'
      });
    });

    // High impact index recommendations
    analysis.highImpactIndexes.forEach(index => {
      recommendations.push({
        type: 'OPTIMIZE_INDEX',
        priority: 'HIGH',
        index: index.name,
        reason: `High impact index with score: ${index.impactScore}`,
        suggestion: 'Consider optimizing or creating covering index variants',
        risk: 'High - critical for query performance'
      });
    });

    return recommendations.sort((a, b) => {
      const priorityOrder = { 'HIGH': 3, 'MEDIUM': 2, 'LOW': 1 };
      return priorityOrder[b.priority] - priorityOrder[a.priority];
    });
  }
}

SQL-Style Index Management with QueryLeaf

QueryLeaf provides familiar SQL syntax for MongoDB index management and optimization:

-- QueryLeaf advanced indexing with SQL-familiar syntax

-- Create comprehensive compound indexes using ESR pattern optimization
CREATE INDEX idx_users_esr_optimized ON users (
  -- Equality fields first (highest selectivity)
  status,           -- Equality filter: active, premium, trial
  subscription_tier, -- Equality filter: basic, premium, enterprise

  -- Sort fields second (maintain sort order)
  created_at DESC,  -- Sort field for chronological ordering
  last_login_at DESC, -- Sort field for activity-based ordering

  -- Range fields last (lowest selectivity impact)  
  total_spent,      -- Range filter for value-based queries
  account_score     -- Range filter for scoring queries
)
WITH INDEX_OPTIONS (
  background = true,
  name = 'idx_users_comprehensive_esr',

  -- Partial filter for active users only (reduces index size by ~70%)
  partial_filter = {
    status: { $in: ['active', 'premium', 'trial'] },
    subscription_tier: { $ne: null },
    last_login_at: { $gte: DATE('2024-01-01') }
  },

  -- Optimization hints
  optimization_level = 'aggressive',
  estimated_selectivity = 0.15,
  expected_query_patterns = ['user_dashboard', 'admin_user_list', 'billing_reports']
);

-- Advanced compound index with covering capability
CREATE COVERING INDEX idx_orders_comprehensive ON orders (
  -- Key fields (used in WHERE and ORDER BY)
  user_id,          -- Join field for user lookups
  status,           -- Filter field: pending, completed, cancelled
  order_date DESC,  -- Sort field for chronological ordering

  -- Included fields (returned in SELECT without document lookup)  
  INCLUDE (
    total_amount,
    discount_amount,
    payment_method,
    shipping_address,
    product_categories,
    order_notes
  )
)
WITH INDEX_OPTIONS (
  background = true,
  name = 'idx_orders_user_status_covering',

  -- Partial filter for recent orders
  partial_filter = {
    order_date: { $gte: DATE_SUB(CURRENT_DATE, INTERVAL 2 YEAR) },
    status: { $in: ['pending', 'processing', 'completed', 'shipped'] }
  },

  covering_optimization = true,
  estimated_coverage = '85% of order queries',
  storage_overhead = 'moderate'
);

-- Specialized indexes for different query patterns
CREATE TEXT INDEX idx_products_search ON products (
  product_name,
  description,
  tags,
  category
)
WITH TEXT_OPTIONS (
  default_language = 'english',
  language_override = 'language_field',
  weights = {
    product_name: 10,
    description: 5,  
    tags: 8,
    category: 3
  },
  text_index_version = 3
);

-- Geospatial index for location-based queries
CREATE GEOSPATIAL INDEX idx_stores_location ON stores (
  location  -- GeoJSON Point field
)
WITH GEO_OPTIONS (
  index_version = '2dsphere_v3',
  coordinate_system = 'WGS84',
  sparse = true,
  background = true
);

-- TTL index for session management
CREATE TTL INDEX idx_sessions_expiry ON user_sessions (
  created_at
)
WITH TTL_OPTIONS (
  expire_after_seconds = 3600,  -- 1 hour
  background = true,
  sparse = true
);

-- Partial index for selective filtering (high-value customers only)
CREATE PARTIAL INDEX idx_users_premium ON users (
  email,
  last_login_at DESC,
  total_lifetime_value DESC
)
WHERE subscription_tier IN ('premium', 'enterprise') 
  AND total_lifetime_value > 1000
  AND status = 'active'
WITH INDEX_OPTIONS (
  background = true,
  estimated_size_reduction = '80%',
  target_queries = ['premium_customer_analysis', 'high_value_user_reports']
);

-- Multi-key index for array fields
CREATE MULTIKEY INDEX idx_orders_products ON orders (
  product_ids,      -- Array field
  order_date DESC,
  total_amount
)
WITH INDEX_OPTIONS (
  background = true,
  multikey_optimization = true,
  array_field_hints = ['product_ids']
);

-- Comprehensive index analysis and optimization query
WITH index_usage_analysis AS (
  SELECT 
    collection_name,
    index_name,
    index_key,
    index_size_mb,
    access_count,
    access_rate_per_hour,

    -- Index efficiency metrics
    ROUND((access_count::float / GREATEST(index_size_mb, 0.1))::numeric, 2) as efficiency_ratio,

    -- Usage categorization
    CASE 
      WHEN access_rate_per_hour > 100 THEN 'critical'
      WHEN access_rate_per_hour > 10 THEN 'high_usage'
      WHEN access_rate_per_hour > 1 THEN 'moderate_usage'
      WHEN access_rate_per_hour > 0.1 THEN 'low_usage'
      ELSE 'unused'
    END as usage_category,

    -- Performance impact assessment
    CASE
      WHEN access_rate_per_hour > 50 AND efficiency_ratio > 10 THEN 'high_impact'
      WHEN access_rate_per_hour > 10 AND efficiency_ratio > 5 THEN 'medium_impact'  
      WHEN access_count > 0 THEN 'low_impact'
      ELSE 'no_impact'
    END as performance_impact,

    -- Storage overhead analysis
    CASE
      WHEN index_size_mb > 1000 THEN 'very_large'
      WHEN index_size_mb > 100 THEN 'large'
      WHEN index_size_mb > 10 THEN 'medium'
      ELSE 'small'
    END as storage_overhead

  FROM index_statistics
  WHERE collection_name IN ('users', 'orders', 'products', 'sessions')
),

query_pattern_analysis AS (
  SELECT 
    collection_name,
    query_shape,
    query_frequency,
    avg_execution_time_ms,
    avg_docs_examined,
    avg_docs_returned,

    -- Query efficiency metrics
    avg_docs_returned::float / GREATEST(avg_docs_examined, 1) as query_efficiency,

    -- Performance classification
    CASE
      WHEN avg_execution_time_ms > 1000 THEN 'slow'
      WHEN avg_execution_time_ms > 100 THEN 'moderate'  
      ELSE 'fast'
    END as performance_category,

    -- Index usage effectiveness
    CASE
      WHEN index_hit_rate > 0.9 THEN 'excellent_index_usage'
      WHEN index_hit_rate > 0.7 THEN 'good_index_usage'
      WHEN index_hit_rate > 0.5 THEN 'fair_index_usage'
      ELSE 'poor_index_usage'
    END as index_effectiveness

  FROM query_performance_log
  WHERE execution_timestamp >= CURRENT_TIMESTAMP - INTERVAL '7 days'
    AND query_frequency >= 10  -- Filter low-frequency queries
),

index_optimization_recommendations AS (
  SELECT 
    iu.collection_name,
    iu.index_name,
    iu.usage_category,
    iu.performance_impact,
    iu.storage_overhead,
    iu.efficiency_ratio,

    -- Optimization recommendations based on usage patterns
    CASE 
      WHEN iu.usage_category = 'unused' AND iu.index_name != '_id_' THEN 
        'DROP - Index is unused and consuming storage'
      WHEN iu.usage_category = 'low_usage' AND iu.efficiency_ratio < 1 THEN
        'REVIEW - Low usage and poor efficiency, consider dropping'
      WHEN iu.performance_impact = 'high_impact' AND iu.storage_overhead = 'very_large' THEN
        'OPTIMIZE - Consider partial index or covering index alternative'  
      WHEN iu.usage_category = 'critical' AND qp.performance_category = 'slow' THEN
        'ENHANCE - Critical index supporting slow queries, needs optimization'
      WHEN iu.efficiency_ratio > 50 AND iu.performance_impact = 'high_impact' THEN
        'MAINTAIN - Well-performing index, continue monitoring'
      ELSE 'MONITOR - Acceptable performance, regular monitoring recommended'
    END as recommendation,

    -- Priority calculation
    CASE 
      WHEN iu.performance_impact = 'high_impact' AND qp.performance_category = 'slow' THEN 'CRITICAL'
      WHEN iu.usage_category = 'unused' AND iu.storage_overhead = 'very_large' THEN 'HIGH'
      WHEN iu.efficiency_ratio < 1 AND iu.storage_overhead IN ('large', 'very_large') THEN 'MEDIUM'
      ELSE 'LOW'
    END as priority,

    -- Estimated impact
    CASE
      WHEN iu.usage_category = 'unused' THEN 
        CONCAT('Storage savings: ', iu.index_size_mb, 'MB')
      WHEN iu.performance_impact = 'high_impact' THEN
        CONCAT('Query performance: ', ROUND(qp.avg_execution_time_ms * 0.3), 'ms reduction potential')
      ELSE 'Minimal impact expected'
    END as estimated_impact

  FROM index_usage_analysis iu
  LEFT JOIN query_pattern_analysis qp ON iu.collection_name = qp.collection_name
)

SELECT 
  collection_name,
  index_name,
  usage_category,
  performance_impact,
  recommendation,
  priority,
  estimated_impact,

  -- Action items
  CASE priority
    WHEN 'CRITICAL' THEN 'Immediate action required - review within 24 hours'
    WHEN 'HIGH' THEN 'Schedule optimization within 1 week'
    WHEN 'MEDIUM' THEN 'Include in next maintenance window'
    ELSE 'Monitor and review quarterly'
  END as action_timeline,

  -- Technical implementation guidance
  CASE 
    WHEN recommendation LIKE 'DROP%' THEN 
      CONCAT('Execute: DROP INDEX ', collection_name, '.', index_name)
    WHEN recommendation LIKE 'OPTIMIZE%' THEN
      'Analyze query patterns and create optimized compound index'
    WHEN recommendation LIKE 'ENHANCE%' THEN
      'Review index field order and consider covering index'
    ELSE 'Continue current monitoring procedures'
  END as implementation_guidance

FROM index_optimization_recommendations
WHERE priority IN ('CRITICAL', 'HIGH', 'MEDIUM')
ORDER BY 
  CASE priority WHEN 'CRITICAL' THEN 1 WHEN 'HIGH' THEN 2 WHEN 'MEDIUM' THEN 3 ELSE 4 END,
  collection_name,
  index_name;

-- Real-time index performance monitoring
CREATE MATERIALIZED VIEW index_performance_dashboard AS
WITH real_time_metrics AS (
  SELECT 
    collection_name,
    index_name,
    DATE_TRUNC('minute', access_timestamp) as minute_bucket,

    -- Real-time utilization metrics
    COUNT(*) as accesses_per_minute,
    AVG(query_execution_time_ms) as avg_query_time,
    SUM(docs_examined) as total_docs_examined,
    SUM(docs_returned) as total_docs_returned,

    -- Index efficiency in real-time
    SUM(docs_returned)::float / GREATEST(SUM(docs_examined), 1) as real_time_efficiency,

    -- Performance trends
    LAG(COUNT(*)) OVER (
      PARTITION BY collection_name, index_name 
      ORDER BY DATE_TRUNC('minute', access_timestamp)
    ) as prev_minute_accesses,

    LAG(AVG(query_execution_time_ms)) OVER (
      PARTITION BY collection_name, index_name
      ORDER BY DATE_TRUNC('minute', access_timestamp)  
    ) as prev_minute_avg_time

  FROM index_access_log
  WHERE access_timestamp >= CURRENT_TIMESTAMP - INTERVAL '1 hour'
  GROUP BY collection_name, index_name, DATE_TRUNC('minute', access_timestamp)
),

performance_alerts AS (
  SELECT 
    collection_name,
    index_name,
    minute_bucket,
    accesses_per_minute,
    avg_query_time,
    real_time_efficiency,

    -- Performance change indicators
    CASE 
      WHEN prev_minute_accesses IS NOT NULL THEN
        ((accesses_per_minute - prev_minute_accesses)::float / prev_minute_accesses * 100)
      ELSE 0
    END as access_rate_change_pct,

    CASE
      WHEN prev_minute_avg_time IS NOT NULL THEN
        ((avg_query_time - prev_minute_avg_time)::float / prev_minute_avg_time * 100) 
      ELSE 0
    END as latency_change_pct,

    -- Alert conditions
    CASE
      WHEN avg_query_time > 1000 THEN 'HIGH_LATENCY_ALERT'
      WHEN real_time_efficiency < 0.1 THEN 'LOW_EFFICIENCY_ALERT'
      WHEN accesses_per_minute > 1000 THEN 'HIGH_LOAD_ALERT'
      WHEN prev_minute_accesses IS NOT NULL AND 
           accesses_per_minute > prev_minute_accesses * 5 THEN 'LOAD_SPIKE_ALERT'
      ELSE 'NORMAL'
    END as alert_status,

    -- Optimization suggestions
    CASE
      WHEN avg_query_time > 1000 AND real_time_efficiency < 0.2 THEN 
        'Consider index redesign or query optimization'
      WHEN accesses_per_minute > 500 AND real_time_efficiency > 0.8 THEN
        'High-performing index under load - monitor for scaling needs'
      WHEN real_time_efficiency < 0.1 THEN
        'Poor selectivity - review partial index opportunities'
      ELSE 'Performance within acceptable parameters'
    END as optimization_suggestion

  FROM real_time_metrics
  WHERE minute_bucket >= CURRENT_TIMESTAMP - INTERVAL '15 minutes'
)

SELECT 
  collection_name,
  index_name,
  ROUND(AVG(accesses_per_minute)::numeric, 1) as avg_accesses_per_minute,
  ROUND(AVG(avg_query_time)::numeric, 2) as avg_latency_ms,
  ROUND(AVG(real_time_efficiency)::numeric, 3) as avg_efficiency,
  ROUND(AVG(access_rate_change_pct)::numeric, 1) as avg_load_change_pct,
  ROUND(AVG(latency_change_pct)::numeric, 1) as avg_latency_change_pct,

  -- Alert summary
  COUNT(*) FILTER (WHERE alert_status != 'NORMAL') as alert_count,
  STRING_AGG(DISTINCT alert_status, ', ') FILTER (WHERE alert_status != 'NORMAL') as active_alerts,
  MODE() WITHIN GROUP (ORDER BY optimization_suggestion) as primary_recommendation,

  -- Performance status
  CASE 
    WHEN COUNT(*) FILTER (WHERE alert_status LIKE '%HIGH%') > 0 THEN 'ATTENTION_REQUIRED'
    WHEN AVG(real_time_efficiency) > 0.7 AND AVG(avg_query_time) < 100 THEN 'OPTIMAL'
    WHEN AVG(real_time_efficiency) > 0.5 AND AVG(avg_query_time) < 250 THEN 'GOOD'  
    ELSE 'NEEDS_OPTIMIZATION'
  END as overall_status

FROM performance_alerts
GROUP BY collection_name, index_name
ORDER BY 
  CASE overall_status 
    WHEN 'ATTENTION_REQUIRED' THEN 1 
    WHEN 'NEEDS_OPTIMIZATION' THEN 2
    WHEN 'GOOD' THEN 3
    WHEN 'OPTIMAL' THEN 4
  END,
  avg_accesses_per_minute DESC;

-- QueryLeaf provides comprehensive indexing capabilities:
-- 1. SQL-familiar syntax for complex MongoDB index creation and management
-- 2. Advanced compound index design with ESR pattern optimization
-- 3. Partial and covering index support for storage and performance optimization
-- 4. Specialized index types: text, geospatial, TTL, sparse, and multikey indexes
-- 5. Real-time index performance monitoring and alerting
-- 6. Automated optimization recommendations based on usage patterns
-- 7. Production-ready index management with background creation and maintenance
-- 8. Comprehensive index analysis and resource utilization tracking
-- 9. Cross-collection optimization opportunities identification  
-- 10. Integration with MongoDB's native indexing capabilities and query optimizer

Best Practices for Production Index Management

Index Design Strategy

Essential principles for effective MongoDB index design and management:

  1. ESR Pattern Application: Design compound indexes following Equality, Sort, Range field ordering for optimal performance
  2. Selective Filtering: Use partial indexes for selective data filtering to reduce storage overhead and improve performance
  3. Covering Index Design: Create covering indexes for frequently accessed query patterns to eliminate document retrieval
  4. Index Consolidation: Minimize index count by designing compound indexes that support multiple query patterns
  5. Performance Monitoring: Implement comprehensive index utilization monitoring and automated optimization
  6. Maintenance Planning: Schedule regular index maintenance and optimization during low-traffic periods

Production Optimization Workflow

Optimize MongoDB indexes systematically for production environments:

  1. Usage Analysis: Analyze actual index usage patterns using database profiler and index statistics
  2. Query Pattern Recognition: Identify common query patterns and optimize indexes for primary use cases
  3. Performance Validation: Validate index performance improvements with comprehensive testing
  4. Resource Management: Balance query performance with storage overhead and maintenance costs
  5. Continuous Monitoring: Implement ongoing performance monitoring and automated alert systems
  6. Iterative Optimization: Regularly review and refine indexing strategies based on evolving query patterns

Conclusion

MongoDB's advanced indexing capabilities provide comprehensive tools for optimizing database performance through sophisticated compound indexes, partial filtering, covering indexes, and specialized index types. The flexible indexing architecture enables developers to design highly optimized indexes that support complex query patterns while minimizing storage overhead and maintenance costs.

Key MongoDB Advanced Indexing benefits include:

  • Comprehensive Index Types: Support for compound, partial, covering, text, geospatial, TTL, and sparse indexes
  • ESR Pattern Optimization: Systematic compound index design following proven optimization patterns
  • Performance Intelligence: Advanced index utilization analysis and automated optimization recommendations
  • Production-Ready Management: Sophisticated index creation, maintenance, and monitoring capabilities
  • Resource Optimization: Intelligent index design that balances performance with storage efficiency
  • Query Pattern Adaptation: Flexible indexing strategies that adapt to evolving application requirements

Whether you're optimizing existing applications, designing new database schemas, or implementing production indexing strategies, MongoDB's advanced indexing capabilities with QueryLeaf's familiar SQL interface provide the foundation for high-performance database operations.

QueryLeaf Integration: QueryLeaf automatically manages MongoDB indexing strategies while providing SQL-familiar syntax for index creation, analysis, and optimization. Advanced indexing patterns, performance monitoring capabilities, and production-ready index management are seamlessly handled through familiar SQL constructs, making sophisticated database optimization both powerful and accessible to SQL-oriented development teams.

The combination of MongoDB's flexible indexing architecture with SQL-style index management makes it an ideal platform for applications requiring both high-performance queries and familiar database optimization patterns, ensuring your applications achieve optimal performance while remaining maintainable and scalable as they grow.

MongoDB Replica Sets and High Availability: Advanced Disaster Recovery and Fault Tolerance Strategies for Mission-Critical Applications

Mission-critical applications require database infrastructure that can withstand hardware failures, network outages, and data center disasters while maintaining continuous availability and data consistency. Traditional database replication approaches often introduce complexity, performance overhead, and operational challenges that become increasingly problematic as application scale and reliability requirements grow.

MongoDB's replica set architecture provides sophisticated high availability and disaster recovery capabilities that eliminate single points of failure while maintaining strong data consistency and automatic failover functionality. Unlike traditional master-slave replication systems with manual failover processes, MongoDB replica sets offer self-healing infrastructure with intelligent election algorithms, configurable read preferences, and comprehensive disaster recovery features that ensure business continuity even during catastrophic failures.

The Traditional Database Replication Challenge

Conventional database replication systems have significant limitations for high-availability requirements:

-- Traditional PostgreSQL streaming replication - manual failover and limited flexibility

-- Primary server configuration (postgresql.conf)
wal_level = replica
max_wal_senders = 3
wal_keep_segments = 64
archive_mode = on
archive_command = 'cp %p /var/lib/postgresql/wal_archive/%f'

-- Standby server configuration (recovery.conf)  
standby_mode = 'on'
primary_conninfo = 'host=primary-server port=5432 user=replicator'
restore_command = 'cp /var/lib/postgresql/wal_archive/%f %p'
trigger_file = '/tmp/postgresql.trigger.5432'

-- Manual failover process (complex and error-prone)
-- 1. Detect primary failure through monitoring
SELECT pg_is_in_recovery(); -- Check if server is in standby mode

-- 2. Promote standby to primary (manual intervention required)
-- Touch trigger file on standby server
-- $ touch /tmp/postgresql.trigger.5432

-- 3. Redirect application traffic (requires external load balancer configuration)
-- Update DNS/load balancer to point to new primary
-- Verify all applications can connect to new primary

-- 4. Reconfigure remaining servers (manual process)
-- Update primary_conninfo on other standby servers
-- Restart PostgreSQL services with new configuration

-- Complex query for checking replication lag
WITH replication_status AS (
  SELECT 
    client_addr,
    client_hostname,
    state,
    sent_lsn,
    write_lsn,
    flush_lsn,
    replay_lsn,
    write_lag,
    flush_lag,
    replay_lag,
    sync_priority,
    sync_state,

    -- Calculate replication delay in bytes
    pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) as replay_delay_bytes,

    -- Check if standby is healthy
    CASE 
      WHEN state = 'streaming' AND pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) < 16777216 THEN 'healthy'
      WHEN state = 'streaming' AND pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) < 134217728 THEN 'lagging'
      WHEN state = 'streaming' THEN 'severely_lagging'
      ELSE 'disconnected'
    END as health_status,

    -- Estimate recovery time if primary fails
    CASE 
      WHEN replay_lag IS NOT NULL THEN 
        EXTRACT(EPOCH FROM replay_lag)::int
      ELSE 
        GREATEST(
          EXTRACT(EPOCH FROM flush_lag)::int,
          pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) / 16777216 * 10
        )
    END as estimated_recovery_seconds

  FROM pg_stat_replication
  WHERE state IS NOT NULL
),

connection_health AS (
  SELECT 
    datname,
    usename,
    client_addr,
    state,
    query,
    state_change,

    -- Connection duration
    EXTRACT(EPOCH FROM (now() - backend_start))::int as connection_age_seconds,

    -- Query duration  
    CASE 
      WHEN state = 'active' THEN EXTRACT(EPOCH FROM (now() - query_start))::int
      ELSE 0
    END as active_query_duration_seconds,

    -- Identify potentially problematic connections
    CASE
      WHEN state = 'idle in transaction' AND (now() - state_change) > interval '5 minutes' THEN 'long_idle_transaction'
      WHEN state = 'active' AND (now() - query_start) > interval '10 minutes' THEN 'long_running_query'
      WHEN backend_type = 'walsender' THEN 'replication_connection'
      ELSE 'normal'
    END as connection_type

  FROM pg_stat_activity
  WHERE backend_type IN ('client backend', 'walsender')
    AND datname IS NOT NULL
)

-- Comprehensive replication monitoring query
SELECT 
  rs.client_addr as standby_server,
  rs.client_hostname as standby_hostname,
  rs.state as replication_state,
  rs.health_status,

  -- Lag information
  COALESCE(EXTRACT(EPOCH FROM rs.replay_lag)::int, 0) as replay_lag_seconds,
  ROUND(rs.replay_delay_bytes / 1048576.0, 2) as replay_delay_mb,
  rs.estimated_recovery_seconds,

  -- Sync configuration
  rs.sync_priority,
  rs.sync_state,

  -- Connection health
  ch.connection_age_seconds,
  ch.active_query_duration_seconds,

  -- Health assessment
  CASE 
    WHEN rs.health_status = 'healthy' AND rs.sync_state = 'sync' THEN 'excellent'
    WHEN rs.health_status = 'healthy' AND rs.sync_state = 'async' THEN 'good'
    WHEN rs.health_status = 'lagging' THEN 'warning'
    WHEN rs.health_status = 'severely_lagging' THEN 'critical'
    ELSE 'unknown'
  END as overall_health,

  -- Failover readiness
  CASE
    WHEN rs.health_status = 'healthy' AND rs.estimated_recovery_seconds < 30 THEN 'ready'
    WHEN rs.health_status IN ('healthy', 'lagging') AND rs.estimated_recovery_seconds < 120 THEN 'acceptable'
    ELSE 'not_ready'
  END as failover_readiness,

  -- Recommendations
  CASE
    WHEN rs.health_status = 'disconnected' THEN 'Check network connectivity and standby server status'
    WHEN rs.health_status = 'severely_lagging' THEN 'Investigate standby performance and network bandwidth'
    WHEN rs.replay_delay_bytes > 134217728 THEN 'Consider increasing wal_keep_segments or using replication slots'
    WHEN rs.sync_state != 'sync' AND rs.sync_priority > 0 THEN 'Review synchronous_standby_names configuration'
    ELSE 'Replication operating normally'
  END as recommendation

FROM replication_status rs
LEFT JOIN connection_health ch ON rs.client_addr = ch.client_addr 
                                AND ch.connection_type = 'replication_connection'
ORDER BY rs.sync_priority DESC, rs.replay_delay_bytes ASC;

-- Problems with traditional PostgreSQL replication:
-- 1. Manual failover process requiring human intervention and expertise
-- 2. Complex configuration management across multiple servers
-- 3. Limited built-in monitoring and health checking capabilities
-- 4. Potential for data loss during failover if not configured properly
-- 5. Application-level connection management complexity
-- 6. No automatic discovery of new primary after failover
-- 7. Split-brain scenarios possible without proper fencing mechanisms
-- 8. Limited geographic distribution capabilities for disaster recovery
-- 9. Difficulty in adding/removing replica servers without downtime
-- 10. Complex backup and point-in-time recovery coordination across replicas

-- Additional monitoring complexity
-- Check for replication slots to prevent WAL accumulation
SELECT 
  slot_name,
  plugin,
  slot_type,
  datoid,
  database,
  temporary,
  active,
  active_pid,
  xmin,
  catalog_xmin,
  restart_lsn,
  confirmed_flush_lsn,

  -- Calculate slot lag
  pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn) as slot_lag_bytes,

  -- Check if slot is causing WAL retention
  CASE 
    WHEN active = false THEN 'inactive_slot'
    WHEN pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn) > 1073741824 THEN 'excessive_lag'
    ELSE 'healthy'
  END as slot_status

FROM pg_replication_slots
ORDER BY slot_lag_bytes DESC;

-- MySQL replication (even more limited)
-- Master configuration
log-bin=mysql-bin
server-id=1
binlog-format=ROW
sync-binlog=1
innodb-flush-log-at-trx-commit=1

-- Slave configuration  
server-id=2
relay-log=mysql-relay
read-only=1

-- Basic replication status (limited information)
SHOW SLAVE STATUS\G

-- Manual failover process (basic and risky)
STOP SLAVE;
RESET SLAVE ALL;
-- Manually change master configuration

-- MySQL replication limitations:
-- - Even more manual failover process
-- - Limited monitoring and diagnostics
-- - Poor handling of network partitions
-- - Basic conflict resolution
-- - Limited geographic replication support
-- - Minimal built-in health checking
-- - Simple master-slave topology only

MongoDB provides comprehensive high availability through replica sets:

// MongoDB Replica Sets - automatic failover with advanced high availability features
const { MongoClient } = require('mongodb');

// Advanced MongoDB Replica Set Management and High Availability System
class MongoReplicaSetManager {
  constructor(connectionString) {
    this.connectionString = connectionString;
    this.client = null;
    this.db = null;

    // High availability configuration
    this.replicaSetConfig = {
      members: [],
      settings: {
        chainingAllowed: true,
        heartbeatIntervalMillis: 2000,
        heartbeatTimeoutSecs: 10,
        electionTimeoutMillis: 10000,
        catchUpTimeoutMillis: 60000,
        getLastErrorModes: {},
        getLastErrorDefaults: { w: 1, wtimeout: 0 }
      }
    };

    this.healthMetrics = new Map();
    this.failoverHistory = [];
    this.performanceTargets = {
      maxReplicationLagSeconds: 10,
      maxElectionTimeSeconds: 30,
      minHealthyMembers: 2
    };
  }

  async initializeReplicaSet(members, options = {}) {
    console.log('Initializing MongoDB replica set with advanced high availability...');

    const {
      replicaSetName = 'rs0',
      priority = { primary: 1, secondary: 0.5, arbiter: 0 },
      tags = {},
      writeConcern = { w: 'majority', j: true },
      readPreference = 'primaryPreferred'
    } = options;

    try {
      // Connect to the primary candidate
      this.client = new MongoClient(this.connectionString, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        replicaSet: replicaSetName,
        readPreference: readPreference,
        writeConcern: writeConcern,
        maxPoolSize: 10,
        serverSelectionTimeoutMS: 5000,
        socketTimeoutMS: 45000,
        heartbeatFrequencyMS: 10000,
        retryWrites: true,
        retryReads: true
      });

      await this.client.connect();
      this.db = this.client.db('admin');

      // Build replica set configuration
      const replicaSetConfig = {
        _id: replicaSetName,
        version: 1,
        members: members.map((member, index) => ({
          _id: index,
          host: member.host,
          priority: member.priority || priority[member.type] || 1,
          votes: member.type === 'arbiter' ? 1 : 1,
          arbiterOnly: member.type === 'arbiter',
          buildIndexes: member.type !== 'arbiter',
          hidden: member.hidden || false,
          slaveDelay: member.slaveDelay || 0,
          tags: { ...tags[member.type], region: member.region, datacenter: member.datacenter }
        })),
        settings: {
          chainingAllowed: true,
          heartbeatIntervalMillis: 2000,
          heartbeatTimeoutSecs: 10,
          electionTimeoutMillis: 10000,
          catchUpTimeoutMillis: 60000,

          // Advanced write concern configurations
          getLastErrorModes: {
            multiDataCenter: { datacenter: 2 },
            majority: { region: 2 }
          },
          getLastErrorDefaults: { 
            w: 'majority', 
            j: true,
            wtimeout: 10000 
          }
        }
      };

      // Initialize replica set
      const initResult = await this.db.runCommand({
        replSetInitiate: replicaSetConfig
      });

      if (initResult.ok === 1) {
        console.log('Replica set initialized successfully');

        // Wait for primary election
        await this.waitForPrimaryElection();

        // Perform initial health check
        const healthStatus = await this.performHealthCheck();

        // Setup monitoring
        await this.setupAdvancedMonitoring();

        console.log('Replica set ready for high availability operations');
        return {
          success: true,
          replicaSetName: replicaSetName,
          members: members,
          healthStatus: healthStatus
        };
      } else {
        throw new Error(`Replica set initialization failed: ${initResult.errmsg}`);
      }

    } catch (error) {
      console.error('Replica set initialization error:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  async performComprehensiveHealthCheck() {
    console.log('Performing comprehensive replica set health assessment...');

    const healthReport = {
      timestamp: new Date(),
      replicaSetStatus: null,
      memberHealth: [],
      replicationLag: {},
      electionMetrics: {},
      networkConnectivity: {},
      performanceMetrics: {},
      alerts: [],
      recommendations: []
    };

    try {
      // Get replica set status
      const rsStatus = await this.db.runCommand({ replSetGetStatus: 1 });
      healthReport.replicaSetStatus = {
        name: rsStatus.set,
        primary: rsStatus.members.find(m => m.state === 1)?.name,
        memberCount: rsStatus.members.length,
        healthyMembers: rsStatus.members.filter(m => [1, 2, 7].includes(m.state)).length,
        state: rsStatus.myState
      };

      // Analyze each member
      for (const member of rsStatus.members) {
        const memberHealth = {
          name: member.name,
          state: member.state,
          stateStr: member.stateStr,
          health: member.health,
          uptime: member.uptime,
          lastHeartbeat: member.lastHeartbeat,
          lastHeartbeatRecv: member.lastHeartbeatRecv,
          pingMs: member.pingMs,
          syncSourceHost: member.syncingTo,

          // Calculate replication lag
          replicationLag: member.optimeDate && rsStatus.date ? 
            (rsStatus.date - member.optimeDate) / 1000 : null,

          // Member status assessment
          status: this.assessMemberStatus(member),

          // Performance metrics
          performanceMetrics: {
            heartbeatLatency: member.pingMs,
            connectionHealth: member.health === 1 ? 'healthy' : 'unhealthy',
            stateStability: this.assessStateStability(member)
          }
        };

        healthReport.memberHealth.push(memberHealth);

        // Track replication lag
        if (memberHealth.replicationLag !== null) {
          healthReport.replicationLag[member.name] = memberHealth.replicationLag;
        }
      }

      // Analyze election metrics
      healthReport.electionMetrics = await this.analyzeElectionMetrics(rsStatus);

      // Check network connectivity
      healthReport.networkConnectivity = await this.checkNetworkConnectivity(rsStatus.members);

      // Generate alerts based on thresholds
      healthReport.alerts = this.generateHealthAlerts(healthReport);

      // Generate recommendations
      healthReport.recommendations = this.generateHealthRecommendations(healthReport);

      console.log(`Health check completed: ${healthReport.memberHealth.length} members analyzed`);
      console.log(`Healthy members: ${healthReport.replicaSetStatus.healthyMembers}/${healthReport.replicaSetStatus.memberCount}`);
      console.log(`Alerts generated: ${healthReport.alerts.length}`);

      return healthReport;

    } catch (error) {
      console.error('Health check failed:', error);
      healthReport.error = error.message;
      return healthReport;
    }
  }

  assessMemberStatus(member) {
    const status = {
      overall: 'unknown',
      issues: [],
      strengths: []
    };

    // State-based assessment
    switch (member.state) {
      case 1: // PRIMARY
        status.overall = 'primary';
        status.strengths.push('Acting as primary, accepting writes');
        break;
      case 2: // SECONDARY
        status.overall = 'healthy';
        status.strengths.push('Healthy secondary, replicating data');
        if (member.optimeDate && Date.now() - member.optimeDate > 30000) {
          status.issues.push('Replication lag exceeds 30 seconds');
          status.overall = 'lagging';
        }
        break;
      case 3: // RECOVERING
        status.overall = 'recovering';
        status.issues.push('Member is in recovery state');
        break;
      case 5: // STARTUP2
        status.overall = 'starting';
        status.issues.push('Member is in startup phase');
        break;
      case 6: // UNKNOWN
        status.overall = 'unknown';
        status.issues.push('Member state is unknown');
        break;
      case 7: // ARBITER
        status.overall = 'arbiter';
        status.strengths.push('Functioning arbiter for elections');
        break;
      case 8: // DOWN
        status.overall = 'down';
        status.issues.push('Member is down or unreachable');
        break;
      case 9: // ROLLBACK
        status.overall = 'rollback';
        status.issues.push('Member is performing rollback');
        break;
      case 10: // REMOVED
        status.overall = 'removed';
        status.issues.push('Member has been removed from replica set');
        break;
      default:
        status.overall = 'unknown';
        status.issues.push(`Unexpected state: ${member.state}`);
    }

    // Health-based assessment
    if (member.health !== 1) {
      status.issues.push('Member health check failing');
      if (status.overall === 'healthy') {
        status.overall = 'unhealthy';
      }
    }

    // Network latency assessment
    if (member.pingMs && member.pingMs > 100) {
      status.issues.push(`High network latency: ${member.pingMs}ms`);
    } else if (member.pingMs && member.pingMs < 10) {
      status.strengths.push(`Low network latency: ${member.pingMs}ms`);
    }

    return status;
  }

  async implementAutomaticFailoverTesting() {
    console.log('Implementing automatic failover testing and validation...');

    const failoverTest = {
      testId: require('crypto').randomUUID(),
      timestamp: new Date(),
      phases: [],
      results: {
        success: false,
        totalTimeMs: 0,
        electionTimeMs: 0,
        dataConsistencyVerified: false,
        applicationConnectivityRestored: false
      }
    };

    try {
      // Phase 1: Pre-failover health check
      console.log('Phase 1: Pre-failover health assessment...');
      const preFailoverHealth = await this.performComprehensiveHealthCheck();
      failoverTest.phases.push({
        phase: 'pre_failover_health',
        timestamp: new Date(),
        status: 'completed',
        data: preFailoverHealth
      });

      if (preFailoverHealth.replicaSetStatus.healthyMembers < this.performanceTargets.minHealthyMembers + 1) {
        throw new Error('Insufficient healthy members for safe failover testing');
      }

      // Phase 2: Insert test data for consistency verification
      console.log('Phase 2: Inserting test data for consistency verification...');
      const testCollection = this.client.db('failover_test').collection('consistency_check');
      const testDocuments = Array.from({ length: 100 }, (_, i) => ({
        _id: `failover_test_${failoverTest.testId}_${i}`,
        timestamp: new Date(),
        sequenceNumber: i,
        testData: `Failover test data ${i}`,
        checksum: require('crypto').createHash('md5').update(`test_${i}`).digest('hex')
      }));

      await testCollection.insertMany(testDocuments, { writeConcern: { w: 'majority', j: true } });
      failoverTest.phases.push({
        phase: 'test_data_insertion',
        timestamp: new Date(),
        status: 'completed',
        data: { documentsInserted: testDocuments.length }
      });

      // Phase 3: Simulate primary failure (step down primary)
      console.log('Phase 3: Simulating primary failure...');
      const startTime = Date.now();

      await this.db.runCommand({ replSetStepDown: 60, force: true });

      failoverTest.phases.push({
        phase: 'primary_step_down',
        timestamp: new Date(),
        status: 'completed',
        data: { stepDownInitiated: true }
      });

      // Phase 4: Wait for new primary election
      console.log('Phase 4: Waiting for new primary election...');
      const electionStartTime = Date.now();

      const newPrimary = await this.waitForPrimaryElection(30000); // 30 second timeout
      const electionEndTime = Date.now();

      failoverTest.results.electionTimeMs = electionEndTime - electionStartTime;

      failoverTest.phases.push({
        phase: 'primary_election',
        timestamp: new Date(),
        status: 'completed',
        data: { 
          newPrimary: newPrimary,
          electionTimeMs: failoverTest.results.electionTimeMs
        }
      });

      // Phase 5: Verify data consistency
      console.log('Phase 5: Verifying data consistency...');

      // Reconnect to new primary
      await this.client.close();
      this.client = new MongoClient(this.connectionString, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        readPreference: 'primary'
      });
      await this.client.connect();

      const verificationCollection = this.client.db('failover_test').collection('consistency_check');
      const retrievedDocs = await verificationCollection.find({
        _id: { $regex: `^failover_test_${failoverTest.testId}_` }
      }).toArray();

      const consistencyCheck = {
        expectedCount: testDocuments.length,
        retrievedCount: retrievedDocs.length,
        dataIntegrityVerified: true,
        checksumMatches: 0
      };

      // Verify checksums
      for (const doc of retrievedDocs) {
        const expectedChecksum = require('crypto').createHash('md5')
          .update(`test_${doc.sequenceNumber}`).digest('hex');
        if (doc.checksum === expectedChecksum) {
          consistencyCheck.checksumMatches++;
        }
      }

      consistencyCheck.dataIntegrityVerified = 
        consistencyCheck.expectedCount === consistencyCheck.retrievedCount &&
        consistencyCheck.checksumMatches === consistencyCheck.expectedCount;

      failoverTest.results.dataConsistencyVerified = consistencyCheck.dataIntegrityVerified;

      failoverTest.phases.push({
        phase: 'data_consistency_verification',
        timestamp: new Date(),
        status: 'completed',
        data: consistencyCheck
      });

      // Phase 6: Test application connectivity
      console.log('Phase 6: Testing application connectivity...');

      try {
        // Simulate application operations
        await verificationCollection.insertOne({
          _id: `post_failover_${failoverTest.testId}`,
          timestamp: new Date(),
          message: 'Post-failover connectivity test'
        }, { writeConcern: { w: 'majority' } });

        const postFailoverDoc = await verificationCollection.findOne({
          _id: `post_failover_${failoverTest.testId}`
        });

        failoverTest.results.applicationConnectivityRestored = postFailoverDoc !== null;

      } catch (error) {
        console.error('Application connectivity test failed:', error);
        failoverTest.results.applicationConnectivityRestored = false;
      }

      failoverTest.phases.push({
        phase: 'application_connectivity_test',
        timestamp: new Date(),
        status: failoverTest.results.applicationConnectivityRestored ? 'completed' : 'failed',
        data: { connectivityRestored: failoverTest.results.applicationConnectivityRestored }
      });

      // Phase 7: Post-failover health check
      console.log('Phase 7: Post-failover health assessment...');
      const postFailoverHealth = await this.performComprehensiveHealthCheck();
      failoverTest.phases.push({
        phase: 'post_failover_health',
        timestamp: new Date(),
        status: 'completed',
        data: postFailoverHealth
      });

      // Calculate total test time
      failoverTest.results.totalTimeMs = Date.now() - startTime;

      // Determine overall success
      failoverTest.results.success = 
        failoverTest.results.electionTimeMs <= (this.performanceTargets.maxElectionTimeSeconds * 1000) &&
        failoverTest.results.dataConsistencyVerified &&
        failoverTest.results.applicationConnectivityRestored &&
        postFailoverHealth.replicaSetStatus.healthyMembers >= this.performanceTargets.minHealthyMembers;

      // Cleanup test data
      await verificationCollection.deleteMany({
        _id: { $regex: `^(failover_test_${failoverTest.testId}_|post_failover_${failoverTest.testId})` }
      });

      console.log(`Failover test completed: ${failoverTest.results.success ? 'SUCCESS' : 'PARTIAL_SUCCESS'}`);
      console.log(`Total failover time: ${failoverTest.results.totalTimeMs}ms`);
      console.log(`Election time: ${failoverTest.results.electionTimeMs}ms`);
      console.log(`Data consistency: ${failoverTest.results.dataConsistencyVerified ? 'VERIFIED' : 'FAILED'}`);
      console.log(`Application connectivity: ${failoverTest.results.applicationConnectivityRestored ? 'RESTORED' : 'FAILED'}`);

      // Record failover test in history
      this.failoverHistory.push(failoverTest);

      return failoverTest;

    } catch (error) {
      console.error('Failover test failed:', error);
      failoverTest.phases.push({
        phase: 'error',
        timestamp: new Date(),
        status: 'failed',
        error: error.message
      });
      failoverTest.results.success = false;
      return failoverTest;
    }
  }

  async setupAdvancedReadPreferences(applications) {
    console.log('Setting up advanced read preferences for optimal performance...');

    const readPreferenceConfigurations = {
      // Real-time dashboard - prefer primary for latest data
      realtime_dashboard: {
        readPreference: 'primary',
        maxStalenessSeconds: 0,
        tags: [],
        description: 'Real-time data requires primary reads',
        useCase: 'Live dashboards, real-time analytics'
      },

      // Reporting queries - can use secondaries with some lag tolerance
      reporting_analytics: {
        readPreference: 'secondaryPreferred',
        maxStalenessSeconds: 30,
        tags: [{ region: 'us-east', workload: 'analytics' }],
        description: 'Analytics workload can tolerate slight lag',
        useCase: 'Business intelligence, historical reports'
      },

      // Geographically distributed reads
      geographic_reads: {
        readPreference: 'nearest',
        maxStalenessSeconds: 60,
        tags: [],
        description: 'Prioritize network proximity for user-facing reads',
        useCase: 'User-facing applications, content delivery'
      },

      // Heavy analytical workloads
      heavy_analytics: {
        readPreference: 'secondary',
        maxStalenessSeconds: 120,
        tags: [{ workload: 'analytics', ssd: 'true' }],
        description: 'Dedicated secondary for heavy analytical queries',
        useCase: 'Data mining, complex aggregations, ML training'
      },

      // Backup and archival operations
      backup_operations: {
        readPreference: 'secondary',
        maxStalenessSeconds: 300,
        tags: [{ backup: 'true', priority: 'low' }],
        description: 'Use dedicated backup secondary',
        useCase: 'Backup operations, data archival, compliance exports'
      }
    };

    const clientConfigurations = {};

    for (const [appName, app] of Object.entries(applications)) {
      const config = readPreferenceConfigurations[app.readPattern] || readPreferenceConfigurations.geographic_reads;

      console.log(`Configuring read preferences for ${appName}:`);
      console.log(`  Pattern: ${app.readPattern}`);
      console.log(`  Read Preference: ${config.readPreference}`);
      console.log(`  Max Staleness: ${config.maxStalenessSeconds}s`);

      clientConfigurations[appName] = {
        connectionString: this.buildConnectionString(config),
        readPreference: config.readPreference,
        readPreferenceTags: config.tags,
        maxStalenessSeconds: config.maxStalenessSeconds,

        // Additional client options for optimization
        options: {
          maxPoolSize: app.connectionPoolSize || 10,
          minPoolSize: app.minConnectionPoolSize || 2,
          maxIdleTimeMS: 30000,
          serverSelectionTimeoutMS: 5000,
          socketTimeoutMS: 45000,
          connectTimeoutMS: 10000,

          // Retry configuration
          retryWrites: true,
          retryReads: true,

          // Write concern based on application requirements
          writeConcern: app.writeConcern || { w: 'majority', j: true },

          // Read concern for consistency requirements
          readConcern: { level: app.readConcern || 'majority' }
        },

        // Monitoring configuration
        monitoring: {
          commandMonitoring: true,
          serverMonitoring: true,
          topologyMonitoring: true
        },

        description: config.description,
        useCase: config.useCase,
        optimizationTips: this.generateReadOptimizationTips(config, app)
      };
    }

    // Setup monitoring for read preference effectiveness
    await this.setupReadPreferenceMonitoring(clientConfigurations);

    console.log(`Read preference configurations created for ${Object.keys(clientConfigurations).length} applications`);

    return clientConfigurations;
  }

  async implementDisasterRecoveryProcedures(options = {}) {
    console.log('Implementing comprehensive disaster recovery procedures...');

    const {
      backupSchedule = 'daily',
      retentionPolicy = { daily: 7, weekly: 4, monthly: 6 },
      geographicDistribution = true,
      automaticFailback = false,
      rtoTarget = 300, // Recovery Time Objective in seconds
      rpoTarget = 60   // Recovery Point Objective in seconds
    } = options;

    const disasterRecoveryPlan = {
      backupStrategy: await this.implementBackupStrategy(backupSchedule, retentionPolicy),
      failoverProcedures: await this.implementFailoverProcedures(rtoTarget),
      recoveryValidation: await this.implementRecoveryValidation(),
      monitoringAndAlerting: await this.setupDisasterRecoveryMonitoring(),
      documentationAndRunbooks: await this.generateDisasterRecoveryRunbooks(),
      testingSchedule: await this.createDisasterRecoveryTestSchedule()
    };

    // Geographic distribution setup
    if (geographicDistribution) {
      disasterRecoveryPlan.geographicDistribution = await this.setupGeographicDistribution();
    }

    // Automatic failback configuration
    if (automaticFailback) {
      disasterRecoveryPlan.automaticFailback = await this.configureAutomaticFailback();
    }

    console.log('Disaster recovery procedures implemented successfully');
    return disasterRecoveryPlan;
  }

  async implementBackupStrategy(schedule, retentionPolicy) {
    console.log('Implementing comprehensive backup strategy...');

    const backupStrategy = {
      hotBackups: {
        enabled: true,
        schedule: schedule,
        method: 'mongodump_with_oplog',
        compression: true,
        encryption: true,
        storageLocation: ['local', 's3', 'gcs'],
        retentionPolicy: retentionPolicy
      },

      continuousBackup: {
        enabled: true,
        oplogTailing: true,
        changeStreams: true,
        pointInTimeRecovery: true,
        maxRecoveryWindow: '7 days'
      },

      consistencyChecks: {
        enabled: true,
        frequency: 'daily',
        validationMethods: ['checksum', 'document_count', 'index_integrity']
      },

      crossRegionReplication: {
        enabled: true,
        regions: ['us-east-1', 'us-west-2', 'eu-west-1'],
        replicationLag: '< 60 seconds'
      }
    };

    // Implement backup automation
    const backupJobs = await this.createAutomatedBackupJobs(backupStrategy);

    return {
      ...backupStrategy,
      automationJobs: backupJobs,
      estimatedRPO: this.calculateEstimatedRPO(backupStrategy),
      storageRequirements: this.calculateStorageRequirements(backupStrategy)
    };
  }

  async waitForPrimaryElection(timeoutMs = 30000) {
    console.log('Waiting for primary election...');

    const startTime = Date.now();
    const pollInterval = 1000; // Check every second

    while (Date.now() - startTime < timeoutMs) {
      try {
        const status = await this.db.runCommand({ replSetGetStatus: 1 });
        const primary = status.members.find(member => member.state === 1);

        if (primary) {
          console.log(`Primary elected: ${primary.name}`);
          return primary.name;
        }

        await new Promise(resolve => setTimeout(resolve, pollInterval));
      } catch (error) {
        // Connection might be lost during election, continue polling
        await new Promise(resolve => setTimeout(resolve, pollInterval));
      }
    }

    throw new Error(`Primary election timeout after ${timeoutMs}ms`);
  }

  generateHealthAlerts(healthReport) {
    const alerts = [];

    // Check for unhealthy members
    const unhealthyMembers = healthReport.memberHealth.filter(m => 
      ['unhealthy', 'down', 'unknown'].includes(m.status.overall)
    );

    if (unhealthyMembers.length > 0) {
      alerts.push({
        severity: 'HIGH',
        type: 'UNHEALTHY_MEMBERS',
        message: `${unhealthyMembers.length} replica set members are unhealthy`,
        members: unhealthyMembers.map(m => m.name),
        impact: 'Reduced fault tolerance and potential for data inconsistency'
      });
    }

    // Check replication lag
    const laggedMembers = Object.entries(healthReport.replicationLag)
      .filter(([, lag]) => lag > this.performanceTargets.maxReplicationLagSeconds);

    if (laggedMembers.length > 0) {
      alerts.push({
        severity: 'MEDIUM',
        type: 'REPLICATION_LAG',
        message: `${laggedMembers.length} members have excessive replication lag`,
        details: Object.fromEntries(laggedMembers),
        impact: 'Potential data loss during failover'
      });
    }

    // Check minimum healthy members threshold
    if (healthReport.replicaSetStatus.healthyMembers < this.performanceTargets.minHealthyMembers) {
      alerts.push({
        severity: 'CRITICAL',
        type: 'INSUFFICIENT_HEALTHY_MEMBERS',
        message: `Only ${healthReport.replicaSetStatus.healthyMembers} healthy members (minimum: ${this.performanceTargets.minHealthyMembers})`,
        impact: 'Risk of complete service outage if another member fails'
      });
    }

    return alerts;
  }

  generateHealthRecommendations(healthReport) {
    const recommendations = [];

    // Analyze member distribution
    const membersByState = healthReport.memberHealth.reduce((acc, member) => {
      acc[member.stateStr] = (acc[member.stateStr] || 0) + 1;
      return acc;
    }, {});

    if (membersByState.SECONDARY < 2) {
      recommendations.push({
        priority: 'HIGH',
        category: 'REDUNDANCY',
        recommendation: 'Add additional secondary members for better fault tolerance',
        reasoning: 'Minimum of 2 secondary members recommended for high availability',
        implementation: 'Use rs.add() to add new replica set members'
      });
    }

    // Check for arbiter usage
    if (membersByState.ARBITER > 0) {
      recommendations.push({
        priority: 'MEDIUM',
        category: 'ARCHITECTURE',
        recommendation: 'Consider replacing arbiters with data-bearing members',
        reasoning: 'Data-bearing members provide better fault tolerance than arbiters',
        implementation: 'Add data-bearing member and remove arbiter when safe'
      });
    }

    // Check geographic distribution
    const regions = new Set(healthReport.memberHealth
      .map(m => m.tags?.region)
      .filter(r => r)
    );

    if (regions.size < 2) {
      recommendations.push({
        priority: 'MEDIUM',
        category: 'DISASTER_RECOVERY',
        recommendation: 'Implement geographic distribution of replica set members',
        reasoning: 'Multi-region deployment protects against datacenter-level failures',
        implementation: 'Deploy members across multiple availability zones or regions'
      });
    }

    return recommendations;
  }

  buildConnectionString(config) {
    // Build MongoDB connection string with read preference options
    const params = new URLSearchParams();

    params.append('readPreference', config.readPreference);

    if (config.maxStalenessSeconds > 0) {
      params.append('maxStalenessSeconds', config.maxStalenessSeconds.toString());
    }

    if (config.tags && config.tags.length > 0) {
      config.tags.forEach((tag, index) => {
        Object.entries(tag).forEach(([key, value]) => {
          params.append(`readPreferenceTags[${index}][${key}]`, value);
        });
      });
    }

    return `${this.connectionString}?${params.toString()}`;
  }

  generateReadOptimizationTips(config, app) {
    const tips = [];

    if (config.readPreference === 'secondary' || config.readPreference === 'secondaryPreferred') {
      tips.push('Consider using connection pooling to maintain connections to multiple secondaries');
      tips.push('Monitor secondary lag to ensure data freshness meets application requirements');
    }

    if (config.maxStalenessSeconds > 60) {
      tips.push('Verify that application logic can handle potentially stale data');
      tips.push('Implement application-level caching for frequently accessed but slow-changing data');
    }

    if (app.queryTypes && app.queryTypes.includes('aggregation')) {
      tips.push('Heavy aggregation workloads benefit from dedicated secondary members with optimized hardware');
      tips.push('Consider using $merge or $out stages to pre-compute results on secondaries');
    }

    return tips;
  }

  async createAutomatedBackupJobs(backupStrategy) {
    // Implementation would create actual backup automation
    // This is a simplified representation
    return {
      dailyHotBackup: {
        schedule: '0 2 * * *', // 2 AM daily
        retention: backupStrategy.hotBackups.retentionPolicy.daily,
        enabled: true
      },
      continuousOplogBackup: {
        enabled: backupStrategy.continuousBackup.enabled,
        method: 'changeStreams'
      },
      weeklyFullBackup: {
        schedule: '0 1 * * 0', // 1 AM Sunday
        retention: backupStrategy.hotBackups.retentionPolicy.weekly,
        enabled: true
      }
    };
  }

  calculateEstimatedRPO(backupStrategy) {
    if (backupStrategy.continuousBackup.enabled) {
      return '< 1 minute'; // With oplog tailing
    } else {
      return '24 hours'; // With daily backups only
    }
  }

  calculateStorageRequirements(backupStrategy) {
    // Simplified storage calculation
    return {
      daily: 'Database size × compression ratio × daily retention',
      weekly: 'Database size × compression ratio × weekly retention', 
      monthly: 'Database size × compression ratio × monthly retention',
      estimated: 'Contact administrator for detailed storage analysis'
    };
  }

  async close() {
    if (this.client) {
      await this.client.close();
    }
  }
}

// Benefits of MongoDB Replica Sets:
// - Automatic failover with intelligent primary election algorithms
// - Strong consistency with configurable write and read concerns
// - Geographic distribution support for disaster recovery
// - Built-in health monitoring and self-healing capabilities
// - Flexible read preference configuration for performance optimization
// - Comprehensive backup and point-in-time recovery options
// - Zero-downtime member addition and removal
// - Advanced replication monitoring and alerting
// - Split-brain prevention through majority-based decisions
// - SQL-compatible high availability management through QueryLeaf integration

module.exports = {
  MongoReplicaSetManager
};

Understanding MongoDB Replica Set Architecture

Advanced High Availability Patterns and Strategies

Implement sophisticated replica set configurations for production environments:

// Advanced replica set patterns for enterprise deployments
class EnterpriseReplicaSetManager extends MongoReplicaSetManager {
  constructor(connectionString, enterpriseConfig) {
    super(connectionString);

    this.enterpriseConfig = {
      multiRegionDeployment: true,
      dedicatedAnalyticsNodes: true,
      priorityBasedElections: true,
      customWriteConcerns: true,
      advancedMonitoring: true,
      ...enterpriseConfig
    };

    this.deploymentTopology = new Map();
    this.performanceOptimizations = new Map();
  }

  async deployGeographicallyDistributedReplicaSet(regions) {
    console.log('Deploying geographically distributed replica set...');

    const topology = {
      regions: regions,
      memberDistribution: this.calculateOptimalMemberDistribution(regions),
      networkLatencyMatrix: await this.measureInterRegionLatency(regions),
      failoverStrategy: this.designFailoverStrategy(regions)
    };

    // Configure members with geographic awareness
    const members = [];
    let memberIndex = 0;

    for (const region of regions) {
      const regionConfig = topology.memberDistribution[region.name];

      for (let i = 0; i < regionConfig.dataMembers; i++) {
        members.push({
          _id: memberIndex++,
          host: `${region.name}-data-${i}.${region.domain}:27017`,
          priority: regionConfig.priority,
          votes: 1,
          tags: {
            region: region.name,
            datacenter: region.datacenter,
            nodeType: 'data',
            ssd: 'true',
            workload: i === 0 ? 'primary' : 'secondary'
          }
        });
      }

      // Add analytics-dedicated members
      if (regionConfig.analyticsMembers > 0) {
        for (let i = 0; i < regionConfig.analyticsMembers; i++) {
          members.push({
            _id: memberIndex++,
            host: `${region.name}-analytics-${i}.${region.domain}:27017`,
            priority: 0, // Never become primary
            votes: 1,
            tags: {
              region: region.name,
              datacenter: region.datacenter,
              nodeType: 'analytics',
              workload: 'analytics',
              ssd: 'true'
            },
            hidden: true // Hidden from application discovery
          });
        }
      }

      // Add arbiter if needed for odd number of voting members
      if (regionConfig.needsArbiter) {
        members.push({
          _id: memberIndex++,
          host: `${region.name}-arbiter.${region.domain}:27017`,
          arbiterOnly: true,
          priority: 0,
          votes: 1,
          tags: {
            region: region.name,
            datacenter: region.datacenter,
            nodeType: 'arbiter'
          }
        });
      }
    }

    // Configure advanced settings for geographic distribution
    const replicaSetConfig = {
      _id: 'global-rs',
      version: 1,
      members: members,
      settings: {
        chainingAllowed: true,
        heartbeatIntervalMillis: 2000,
        heartbeatTimeoutSecs: 10,
        electionTimeoutMillis: 10000,
        catchUpTimeoutMillis: 60000,

        // Custom write concerns for multi-region safety
        getLastErrorModes: {
          // Require writes to be acknowledged by majority in each region
          multiRegion: Object.fromEntries(
            regions.map(r => [r.name, 1])
          ),
          // Require acknowledgment from majority of data centers
          multiDataCenter: { datacenter: Math.ceil(regions.length / 2) },
          // For critical operations, require all regions
          allRegions: Object.fromEntries(
            regions.map(r => [r.name, 1])
          )
        },

        getLastErrorDefaults: {
          w: 'multiRegion',
          j: true,
          wtimeout: 15000 // Higher timeout for geographic distribution
        }
      }
    };

    // Initialize the distributed replica set
    const initResult = await this.initializeReplicaSet(members, {
      replicaSetName: 'global-rs',
      writeConcern: { w: 'multiRegion', j: true },
      readPreference: 'primaryPreferred'
    });

    if (initResult.success) {
      // Configure regional read preferences
      await this.configureRegionalReadPreferences(regions);

      // Setup cross-region monitoring
      await this.setupCrossRegionMonitoring(regions);

      // Validate network connectivity and latency
      await this.validateCrossRegionConnectivity(regions);
    }

    return {
      topology: topology,
      replicaSetConfig: replicaSetConfig,
      initResult: initResult,
      optimizations: await this.generateGlobalOptimizations(topology)
    };
  }

  async implementZeroDowntimeMaintenance(maintenancePlan) {
    console.log('Implementing zero-downtime maintenance procedures...');

    const maintenance = {
      planId: require('crypto').randomUUID(),
      startTime: new Date(),
      phases: [],
      rollbackPlan: null,
      success: false
    };

    try {
      // Phase 1: Pre-maintenance health check
      const preMaintenanceHealth = await this.performComprehensiveHealthCheck();

      if (preMaintenanceHealth.alerts.some(alert => alert.severity === 'CRITICAL')) {
        throw new Error('Cannot perform maintenance: critical health issues detected');
      }

      maintenance.phases.push({
        phase: 'pre_maintenance_health_check',
        status: 'completed',
        timestamp: new Date(),
        data: { healthyMembers: preMaintenanceHealth.replicaSetStatus.healthyMembers }
      });

      // Phase 2: Create maintenance plan execution order
      const executionOrder = this.createMaintenanceExecutionOrder(maintenancePlan, preMaintenanceHealth);

      maintenance.phases.push({
        phase: 'execution_order_planning',
        status: 'completed',
        timestamp: new Date(),
        data: { executionOrder: executionOrder }
      });

      // Phase 3: Execute maintenance on each member
      for (const step of executionOrder) {
        console.log(`Executing maintenance step: ${step.description}`);

        const stepResult = await this.executeMaintenanceStep(step);

        maintenance.phases.push({
          phase: `maintenance_step_${step.memberId}`,
          status: stepResult.success ? 'completed' : 'failed',
          timestamp: new Date(),
          data: stepResult
        });

        if (!stepResult.success && step.critical) {
          throw new Error(`Critical maintenance step failed: ${step.description}`);
        }

        // Wait for member to rejoin and catch up
        if (stepResult.requiresRejoin) {
          await this.waitForMemberRecovery(step.memberId, 300000); // 5 minute timeout
        }

        // Validate cluster health before proceeding
        const intermediateHealth = await this.performComprehensiveHealthCheck();
        if (intermediateHealth.replicaSetStatus.healthyMembers < this.performanceTargets.minHealthyMembers) {
          throw new Error('Insufficient healthy members to continue maintenance');
        }
      }

      // Phase 4: Post-maintenance validation
      const postMaintenanceHealth = await this.performComprehensiveHealthCheck();
      const validationResult = await this.validateMaintenanceCompletion(maintenancePlan, postMaintenanceHealth);

      maintenance.phases.push({
        phase: 'post_maintenance_validation',
        status: validationResult.success ? 'completed' : 'failed',
        timestamp: new Date(),
        data: validationResult
      });

      maintenance.success = validationResult.success;
      maintenance.endTime = new Date();
      maintenance.totalDurationMs = maintenance.endTime - maintenance.startTime;

      console.log(`Zero-downtime maintenance ${maintenance.success ? 'completed successfully' : 'completed with issues'}`);
      console.log(`Total duration: ${maintenance.totalDurationMs}ms`);

      return maintenance;

    } catch (error) {
      console.error('Maintenance procedure failed:', error);

      maintenance.phases.push({
        phase: 'error',
        status: 'failed',
        timestamp: new Date(),
        error: error.message
      });

      // Attempt rollback if configured
      if (maintenance.rollbackPlan) {
        console.log('Attempting rollback...');
        const rollbackResult = await this.executeRollback(maintenance.rollbackPlan);
        maintenance.rollback = rollbackResult;
      }

      maintenance.success = false;
      maintenance.endTime = new Date();
      return maintenance;
    }
  }

  calculateOptimalMemberDistribution(regions) {
    const totalRegions = regions.length;
    const distribution = {};

    if (totalRegions === 1) {
      // Single region deployment
      distribution[regions[0].name] = {
        dataMembers: 3,
        analyticsMembers: 1,
        priority: 1,
        needsArbiter: false
      };
    } else if (totalRegions === 2) {
      // Two region deployment - need arbiter for odd voting members
      distribution[regions[0].name] = {
        dataMembers: 2,
        analyticsMembers: 1,
        priority: 1,
        needsArbiter: false
      };
      distribution[regions[1].name] = {
        dataMembers: 2,
        analyticsMembers: 1,
        priority: 0.5,
        needsArbiter: true // Add arbiter to prevent split-brain
      };
    } else if (totalRegions >= 3) {
      // Multi-region deployment with primary preference
      const primaryRegion = regions[0];
      distribution[primaryRegion.name] = {
        dataMembers: 2,
        analyticsMembers: 1,
        priority: 1,
        needsArbiter: false
      };

      regions.slice(1).forEach((region, index) => {
        distribution[region.name] = {
          dataMembers: 1,
          analyticsMembers: index === 0 ? 1 : 0, // Analytics in first secondary region
          priority: 0.5 - (index * 0.1), // Decreasing priority
          needsArbiter: false
        };
      });
    }

    return distribution;
  }

  async measureInterRegionLatency(regions) {
    console.log('Measuring inter-region network latency...');

    const latencyMatrix = {};

    for (const sourceRegion of regions) {
      latencyMatrix[sourceRegion.name] = {};

      for (const targetRegion of regions) {
        if (sourceRegion.name === targetRegion.name) {
          latencyMatrix[sourceRegion.name][targetRegion.name] = 0;
          continue;
        }

        try {
          // Simulate latency measurement (in production, use actual network tests)
          const estimatedLatency = this.estimateLatencyBetweenRegions(sourceRegion, targetRegion);
          latencyMatrix[sourceRegion.name][targetRegion.name] = estimatedLatency;

        } catch (error) {
          console.warn(`Failed to measure latency between ${sourceRegion.name} and ${targetRegion.name}:`, error.message);
          latencyMatrix[sourceRegion.name][targetRegion.name] = 999; // High value for unreachable
        }
      }
    }

    return latencyMatrix;
  }

  estimateLatencyBetweenRegions(source, target) {
    // Simplified latency estimation based on geographic distance
    const latencyMap = {
      'us-east-1_us-west-2': 70,
      'us-east-1_eu-west-1': 85,
      'us-west-2_eu-west-1': 140,
      'us-east-1_ap-southeast-1': 180,
      'us-west-2_ap-southeast-1': 120,
      'eu-west-1_ap-southeast-1': 160
    };

    const key = `${source.name}_${target.name}`;
    const reverseKey = `${target.name}_${source.name}`;

    return latencyMap[key] || latencyMap[reverseKey] || 200; // Default high latency
  }

  designFailoverStrategy(regions) {
    return {
      primaryRegionFailure: {
        strategy: 'automatic_election',
        timeoutMs: 10000,
        requiredVotes: Math.ceil((regions.length * 2 + 1) / 2) // Majority
      },

      networkPartition: {
        strategy: 'majority_partition_wins',
        description: 'Partition with majority of voting members continues operation'
      },

      crossRegionReplication: {
        strategy: 'eventual_consistency',
        maxLagSeconds: 60,
        description: 'Accept eventual consistency during network issues'
      }
    };
  }

  async waitForMemberRecovery(memberId, timeoutMs) {
    console.log(`Waiting for member ${memberId} to recover...`);

    const startTime = Date.now();
    const pollInterval = 5000; // Check every 5 seconds

    while (Date.now() - startTime < timeoutMs) {
      try {
        const status = await this.db.runCommand({ replSetGetStatus: 1 });
        const member = status.members.find(m => m._id === memberId);

        if (member && [1, 2].includes(member.state)) { // PRIMARY or SECONDARY
          console.log(`Member ${memberId} recovered successfully`);
          return true;
        }

        await new Promise(resolve => setTimeout(resolve, pollInterval));
      } catch (error) {
        console.warn(`Error checking member ${memberId} status:`, error.message);
        await new Promise(resolve => setTimeout(resolve, pollInterval));
      }
    }

    throw new Error(`Member ${memberId} recovery timeout after ${timeoutMs}ms`);
  }

  createMaintenanceExecutionOrder(maintenancePlan, healthStatus) {
    const executionOrder = [];

    // Always start with secondaries, then primary
    const secondaries = healthStatus.memberHealth
      .filter(m => m.stateStr === 'SECONDARY')
      .sort((a, b) => (b.priority || 0) - (a.priority || 0)); // Highest priority secondary first

    const primary = healthStatus.memberHealth.find(m => m.stateStr === 'PRIMARY');

    // Add secondary maintenance steps
    secondaries.forEach((member, index) => {
      executionOrder.push({
        memberId: member._id,
        memberName: member.name,
        description: `Maintenance on secondary: ${member.name}`,
        critical: false,
        requiresRejoin: maintenancePlan.requiresRestart,
        estimatedDurationMs: maintenancePlan.estimatedDurationMs || 300000,
        order: index
      });
    });

    // Add primary maintenance step (with step-down)
    if (primary) {
      executionOrder.push({
        memberId: primary._id,
        memberName: primary.name,
        description: `Maintenance on primary: ${primary.name} (with step-down)`,
        critical: true,
        requiresRejoin: maintenancePlan.requiresRestart,
        requiresStepDown: true,
        estimatedDurationMs: (maintenancePlan.estimatedDurationMs || 300000) + 30000, // Extra time for election
        order: secondaries.length
      });
    }

    return executionOrder;
  }

  async executeMaintenanceStep(step) {
    console.log(`Executing maintenance step: ${step.description}`);

    try {
      // Step down primary if required
      if (step.requiresStepDown) {
        console.log(`Stepping down primary: ${step.memberName}`);
        await this.db.runCommand({ 
          replSetStepDown: Math.ceil(step.estimatedDurationMs / 1000) + 60, // Add buffer
          force: false 
        });

        // Wait for new primary election
        await this.waitForPrimaryElection(30000);
      }

      // Simulate maintenance operation (replace with actual maintenance logic)
      console.log(`Performing maintenance on ${step.memberName}...`);
      await new Promise(resolve => setTimeout(resolve, 5000)); // Simulate maintenance work

      return {
        success: true,
        memberId: step.memberId,
        memberName: step.memberName,
        requiresRejoin: step.requiresRejoin,
        completionTime: new Date()
      };

    } catch (error) {
      console.error(`Maintenance step failed for ${step.memberName}:`, error);
      return {
        success: false,
        memberId: step.memberId,
        memberName: step.memberName,
        error: error.message,
        requiresRejoin: false
      };
    }
  }

  async validateMaintenanceCompletion(maintenancePlan, postMaintenanceHealth) {
    console.log('Validating maintenance completion...');

    const validation = {
      success: true,
      checks: [],
      issues: []
    };

    // Check that all members are healthy
    const healthyMembers = postMaintenanceHealth.memberHealth
      .filter(m => ['primary', 'healthy'].includes(m.status.overall));

    validation.checks.push({
      check: 'member_health',
      passed: healthyMembers.length >= this.performanceTargets.minHealthyMembers,
      details: `${healthyMembers.length} healthy members (minimum: ${this.performanceTargets.minHealthyMembers})`
    });

    // Check replication lag
    const maxLag = Math.max(...Object.values(postMaintenanceHealth.replicationLag));
    validation.checks.push({
      check: 'replication_lag',
      passed: maxLag <= this.performanceTargets.maxReplicationLagSeconds,
      details: `Maximum lag: ${maxLag}s (target: ${this.performanceTargets.maxReplicationLagSeconds}s)`
    });

    // Check for any alerts
    const criticalAlerts = postMaintenanceHealth.alerts
      .filter(alert => alert.severity === 'CRITICAL');

    validation.checks.push({
      check: 'critical_alerts',
      passed: criticalAlerts.length === 0,
      details: `${criticalAlerts.length} critical alerts`
    });

    // Overall success determination
    validation.success = validation.checks.every(check => check.passed);

    if (!validation.success) {
      validation.issues = validation.checks
        .filter(check => !check.passed)
        .map(check => `${check.check}: ${check.details}`);
    }

    return validation;
  }
}

SQL-Style Replica Set Management with QueryLeaf

QueryLeaf provides familiar SQL syntax for MongoDB replica set management and monitoring:

-- QueryLeaf replica set management with SQL-familiar syntax

-- Create replica set with advanced configuration
CREATE REPLICA SET global_ecommerce_rs WITH (
  members = [
    { host = 'us-east-primary-1.company.com:27017', priority = 1.0, tags = { region = 'us-east', datacenter = 'dc1' } },
    { host = 'us-east-secondary-1.company.com:27017', priority = 0.5, tags = { region = 'us-east', datacenter = 'dc2' } },
    { host = 'us-west-secondary-1.company.com:27017', priority = 0.3, tags = { region = 'us-west', datacenter = 'dc3' } },
    { host = 'eu-west-secondary-1.company.com:27017', priority = 0.3, tags = { region = 'eu-west', datacenter = 'dc4' } },
    { host = 'analytics-secondary-1.company.com:27017', priority = 0, hidden = true, tags = { workload = 'analytics' } }
  ],

  -- Advanced replica set settings
  heartbeat_interval = '2 seconds',
  election_timeout = '10 seconds',
  catchup_timeout = '60 seconds',

  -- Custom write concerns for multi-region safety
  write_concerns = {
    multi_region = { us_east = 1, us_west = 1, eu_west = 1 },
    majority_datacenter = { datacenter = 3 },
    analytics_safe = { workload_analytics = 0, datacenter = 2 }
  },

  default_write_concern = { w = 'multi_region', j = true, wtimeout = '15 seconds' }
);

-- Monitor replica set health with comprehensive metrics
WITH replica_set_health AS (
  SELECT 
    member_name,
    member_state,
    member_state_str,
    health_status,
    uptime_seconds,
    ping_ms,

    -- Replication lag calculation
    EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP - optime_date)) as replication_lag_seconds,

    -- Member performance assessment
    CASE member_state
      WHEN 1 THEN 'PRIMARY'
      WHEN 2 THEN 'SECONDARY'
      WHEN 7 THEN 'ARBITER'
      WHEN 8 THEN 'DOWN'
      WHEN 3 THEN 'RECOVERING'
      ELSE 'UNKNOWN'
    END as role,

    -- Health grade assignment
    CASE 
      WHEN health_status = 1 AND member_state IN (1, 2) AND ping_ms < 50 THEN 'A'
      WHEN health_status = 1 AND member_state IN (1, 2) AND ping_ms < 100 THEN 'B'
      WHEN health_status = 1 AND member_state IN (1, 2, 7) THEN 'C'
      WHEN health_status = 1 AND member_state NOT IN (1, 2, 7) THEN 'D'
      ELSE 'F'
    END as health_grade,

    -- Network performance indicators
    CASE
      WHEN ping_ms IS NULL THEN 'UNREACHABLE'
      WHEN ping_ms < 10 THEN 'EXCELLENT'
      WHEN ping_ms < 50 THEN 'GOOD'
      WHEN ping_ms < 100 THEN 'ACCEPTABLE'
      WHEN ping_ms < 250 THEN 'POOR'
      ELSE 'CRITICAL'
    END as network_performance,

    -- Extract member tags for analysis
    member_tags.region as member_region,
    member_tags.datacenter as member_datacenter,
    member_tags.workload as member_workload,
    sync_source_host

  FROM rs_status()  -- QueryLeaf function to get replica set status
),

replication_analysis AS (
  SELECT 
    member_region,
    member_datacenter,
    role,

    -- Regional distribution analysis
    COUNT(*) as members_in_region,
    COUNT(*) FILTER (WHERE role = 'SECONDARY') as secondaries_in_region,
    COUNT(*) FILTER (WHERE health_grade IN ('A', 'B')) as healthy_members_in_region,

    -- Performance metrics by region
    AVG(replication_lag_seconds) as avg_replication_lag,
    MAX(replication_lag_seconds) as max_replication_lag,
    AVG(ping_ms) as avg_network_latency,
    MAX(ping_ms) as max_network_latency,

    -- Health distribution
    COUNT(*) FILTER (WHERE health_grade = 'A') as grade_a_members,
    COUNT(*) FILTER (WHERE health_grade = 'B') as grade_b_members,
    COUNT(*) FILTER (WHERE health_grade IN ('D', 'F')) as problematic_members,

    -- Fault tolerance assessment
    CASE
      WHEN COUNT(*) FILTER (WHERE role IN ('PRIMARY', 'SECONDARY') AND health_grade IN ('A', 'B')) >= 2 
      THEN 'FAULT_TOLERANT'
      WHEN COUNT(*) FILTER (WHERE role IN ('PRIMARY', 'SECONDARY')) >= 2 
      THEN 'MINIMAL_REDUNDANCY'
      ELSE 'AT_RISK'
    END as fault_tolerance_status

  FROM replica_set_health
  WHERE role != 'ARBITER'  -- Exclude arbiters from data analysis
  GROUP BY member_region, member_datacenter, role
),

failover_readiness_assessment AS (
  SELECT 
    rh.member_name,
    rh.role,
    rh.health_grade,
    rh.replication_lag_seconds,
    rh.member_region,

    -- Failover readiness scoring
    CASE 
      WHEN rh.role = 'PRIMARY' THEN 'N/A - Current Primary'
      WHEN rh.role = 'SECONDARY' AND rh.health_grade IN ('A', 'B') AND rh.replication_lag_seconds < 10 THEN 'READY'
      WHEN rh.role = 'SECONDARY' AND rh.health_grade = 'C' AND rh.replication_lag_seconds < 30 THEN 'ACCEPTABLE'
      WHEN rh.role = 'SECONDARY' AND rh.replication_lag_seconds < 120 THEN 'DELAYED'
      ELSE 'NOT_READY'
    END as failover_readiness,

    -- Estimated failover time
    CASE 
      WHEN rh.role = 'SECONDARY' AND rh.health_grade IN ('A', 'B') AND rh.replication_lag_seconds < 10 
      THEN '< 15 seconds'
      WHEN rh.role = 'SECONDARY' AND rh.replication_lag_seconds < 60 
      THEN '15-45 seconds'  
      WHEN rh.role = 'SECONDARY' AND rh.replication_lag_seconds < 300 
      THEN '1-5 minutes'
      ELSE '> 5 minutes or unknown'
    END as estimated_failover_time,

    -- Regional failover preference
    ROW_NUMBER() OVER (
      PARTITION BY rh.member_region 
      ORDER BY 
        CASE rh.health_grade WHEN 'A' THEN 1 WHEN 'B' THEN 2 WHEN 'C' THEN 3 ELSE 4 END,
        rh.replication_lag_seconds,
        rh.ping_ms
    ) as regional_failover_preference

  FROM replica_set_health rh
  WHERE rh.role IN ('PRIMARY', 'SECONDARY')
)

-- Comprehensive replica set status report
SELECT 
  'REPLICA SET HEALTH SUMMARY' as report_section,

  -- Overall cluster health
  (SELECT COUNT(*) FROM replica_set_health WHERE health_grade IN ('A', 'B')) as healthy_members,
  (SELECT COUNT(*) FROM replica_set_health WHERE role IN ('PRIMARY', 'SECONDARY')) as data_bearing_members,
  (SELECT COUNT(DISTINCT member_region) FROM replica_set_health) as regions_covered,
  (SELECT COUNT(DISTINCT member_datacenter) FROM replica_set_health) as datacenters_covered,

  -- Performance indicators
  (SELECT ROUND(AVG(replication_lag_seconds)::numeric, 2) FROM replica_set_health WHERE role = 'SECONDARY') as avg_replication_lag_sec,
  (SELECT ROUND(MAX(replication_lag_seconds)::numeric, 2) FROM replica_set_health WHERE role = 'SECONDARY') as max_replication_lag_sec,
  (SELECT ROUND(AVG(ping_ms)::numeric, 1) FROM replica_set_health WHERE ping_ms IS NOT NULL) as avg_network_latency_ms,

  -- Fault tolerance assessment
  (SELECT fault_tolerance_status FROM replication_analysis LIMIT 1) as overall_fault_tolerance,

  -- Failover readiness
  (SELECT COUNT(*) FROM failover_readiness_assessment WHERE failover_readiness = 'READY') as failover_ready_secondaries,
  (SELECT member_name FROM failover_readiness_assessment WHERE regional_failover_preference = 1 AND role = 'SECONDARY' ORDER BY replication_lag_seconds LIMIT 1) as preferred_failover_candidate

UNION ALL

-- Regional distribution analysis
SELECT 
  'REGIONAL DISTRIBUTION' as report_section,

  member_region as region,
  members_in_region,
  secondaries_in_region,  
  healthy_members_in_region,
  ROUND(avg_replication_lag::numeric, 2) as avg_lag_sec,
  ROUND(avg_network_latency::numeric, 1) as avg_latency_ms,
  fault_tolerance_status,

  -- Regional health grade
  CASE 
    WHEN problematic_members = 0 AND grade_a_members >= 1 THEN 'EXCELLENT'
    WHEN problematic_members = 0 AND healthy_members_in_region >= 1 THEN 'GOOD'
    WHEN problematic_members <= 1 THEN 'ACCEPTABLE'
    ELSE 'NEEDS_ATTENTION'
  END as regional_health_grade

FROM replication_analysis
WHERE member_region IS NOT NULL

UNION ALL

-- Failover readiness details
SELECT 
  'FAILOVER READINESS' as report_section,

  member_name,
  role,
  health_grade,
  failover_readiness,
  estimated_failover_time,
  member_region,

  CASE 
    WHEN failover_readiness = 'READY' THEN 'Can handle immediate failover'
    WHEN failover_readiness = 'ACCEPTABLE' THEN 'Can handle failover with short delay'
    WHEN failover_readiness = 'DELAYED' THEN 'Requires catch-up time before failover'
    ELSE 'Not suitable for failover'
  END as failover_notes

FROM failover_readiness_assessment
ORDER BY 
  CASE failover_readiness 
    WHEN 'READY' THEN 1 
    WHEN 'ACCEPTABLE' THEN 2 
    WHEN 'DELAYED' THEN 3 
    ELSE 4 
  END,
  replication_lag_seconds;

-- Advanced read preference configuration
CREATE READ PREFERENCE CONFIGURATION application_read_preferences AS (

  -- Real-time dashboard queries - require primary for consistency
  real_time_dashboard = {
    read_preference = 'primary',
    max_staleness = '0 seconds',
    tags = {},
    description = 'Live dashboards requiring immediate consistency'
  },

  -- Business intelligence queries - can use secondaries
  business_intelligence = {
    read_preference = 'secondaryPreferred',
    max_staleness = '30 seconds', 
    tags = [{ workload = 'analytics' }, { region = 'us-east' }],
    description = 'BI queries with slight staleness tolerance'
  },

  -- Geographic user queries - prefer regional secondaries
  geographic_user_queries = {
    read_preference = 'nearest',
    max_staleness = '60 seconds',
    tags = [{ region = '${user_region}' }],
    description = 'User-facing queries optimized for geographic proximity'
  },

  -- Reporting and archival - use dedicated analytics secondary
  reporting_archival = {
    read_preference = 'secondary',
    max_staleness = '300 seconds',
    tags = [{ workload = 'analytics' }, { hidden = 'true' }],
    description = 'Heavy reporting queries isolated from primary workload'
  },

  -- Backup operations - use specific backup-designated secondary
  backup_operations = {
    read_preference = 'secondary', 
    max_staleness = '600 seconds',
    tags = [{ backup = 'true' }],
    description = 'Backup and compliance operations'
  }
);

-- Automatic failover testing and validation
CREATE FAILOVER TEST PROCEDURE comprehensive_failover_test AS (

  -- Test configuration
  test_duration = '5 minutes',
  data_consistency_validation = true,
  application_connectivity_testing = true,
  performance_impact_measurement = true,

  -- Test phases
  phases = [
    {
      phase = 'pre_test_health_check',
      description = 'Validate cluster health before testing',
      required_healthy_members = 3,
      max_replication_lag = '30 seconds'
    },

    {
      phase = 'test_data_insertion', 
      description = 'Insert test data for consistency verification',
      test_documents = 1000,
      write_concern = { w = 'majority', j = true }
    },

    {
      phase = 'primary_step_down',
      description = 'Force primary to step down',
      step_down_duration = '300 seconds',
      force_step_down = false
    },

    {
      phase = 'election_monitoring',
      description = 'Monitor primary election process', 
      max_election_time = '30 seconds',
      log_election_details = true
    },

    {
      phase = 'connectivity_validation',
      description = 'Test application connectivity to new primary',
      connection_timeout = '10 seconds',
      retry_attempts = 3
    },

    {
      phase = 'data_consistency_check',
      description = 'Verify data consistency after failover',
      verify_test_data = true,
      checksum_validation = true
    },

    {
      phase = 'performance_assessment',
      description = 'Measure failover impact on performance',
      metrics = ['election_time', 'connectivity_restore_time', 'replication_catch_up_time']
    }
  ],

  -- Success criteria
  success_criteria = {
    max_election_time = '30 seconds',
    data_consistency = 'required',
    zero_data_loss = 'required',
    application_connectivity_restore = '< 60 seconds'
  },

  -- Automated scheduling
  schedule = 'monthly',
  notification_recipients = ['[email protected]', '[email protected]']
);

-- Disaster recovery configuration and procedures
CREATE DISASTER RECOVERY PLAN enterprise_dr_plan AS (

  -- Backup strategy
  backup_strategy = {
    hot_backups = {
      frequency = 'daily',
      retention = '30 days',
      compression = true,
      encryption = true,
      storage_locations = ['s3://company-mongo-backups', 'gcs://company-mongo-dr']
    },

    continuous_backup = {
      oplog_tailing = true,
      change_streams = true,
      point_in_time_recovery = true,
      max_recovery_window = '7 days'
    },

    cross_region_replication = {
      enabled = true,
      target_regions = ['us-west-2', 'eu-central-1'],
      replication_lag_target = '< 60 seconds'
    }
  },

  -- Recovery procedures
  recovery_procedures = {

    -- Single member failure
    member_failure = {
      detection_time_target = '< 30 seconds',
      automatic_response = true,
      procedures = [
        'Automatic failover via replica set election',
        'Alert operations team',
        'Provision replacement member',
        'Add replacement to replica set',
        'Monitor replication catch-up'
      ]
    },

    -- Regional failure  
    regional_failure = {
      detection_time_target = '< 2 minutes',
      automatic_response = 'partial',
      procedures = [
        'Automatic failover to available regions',
        'Redirect application traffic',
        'Scale remaining regions for increased load',
        'Provision new regional deployment', 
        'Restore full geographic distribution'
      ]
    },

    -- Complete cluster failure
    complete_failure = {
      detection_time_target = '< 5 minutes',
      automatic_response = false,
      procedures = [
        'Activate disaster recovery plan',
        'Restore from most recent backup',
        'Apply oplog entries for point-in-time recovery',
        'Provision new cluster infrastructure',
        'Validate data integrity',
        'Redirect application traffic to recovered cluster'
      ]
    }
  },

  -- RTO/RPO targets
  recovery_targets = {
    member_failure = { rto = '< 1 minute', rpo = '0 seconds' },
    regional_failure = { rto = '< 5 minutes', rpo = '< 30 seconds' },
    complete_failure = { rto = '< 2 hours', rpo = '< 15 minutes' }
  },

  -- Testing and validation
  testing_schedule = {
    failover_tests = 'monthly',
    disaster_recovery_drills = 'quarterly', 
    backup_restoration_tests = 'weekly',
    cross_region_connectivity_tests = 'daily'
  }
);

-- Real-time monitoring and alerting configuration
CREATE MONITORING CONFIGURATION replica_set_monitoring AS (

  -- Health check intervals
  health_check_interval = '10 seconds',
  performance_sampling_interval = '30 seconds',
  trend_analysis_window = '1 hour',

  -- Alert thresholds
  alert_thresholds = {

    -- Replication lag alerts
    replication_lag = {
      warning = '30 seconds',
      critical = '2 minutes',
      escalation = '5 minutes'
    },

    -- Member health alerts  
    member_health = {
      warning = 'any_member_down',
      critical = 'primary_down_or_majority_unavailable',
      escalation = 'split_brain_detected'
    },

    -- Network latency alerts
    network_latency = {
      warning = '100 ms average',
      critical = '500 ms average', 
      escalation = 'member_unreachable'
    },

    -- Election frequency alerts
    election_frequency = {
      warning = '2 elections per hour',
      critical = '5 elections per hour',
      escalation = 'continuous_election_cycling'
    }
  },

  -- Notification configuration
  notifications = {
    email = ['[email protected]', '[email protected]'],
    slack = '#database-alerts',
    pagerduty = 'mongodb-replica-set-service',
    webhook = 'https://monitoring.company.com/mongodb-alerts'
  },

  -- Automated responses
  automated_responses = {
    member_down = 'log_alert_and_notify',
    high_replication_lag = 'investigate_and_notify',
    primary_election = 'log_details_and_validate_health',
    split_brain_detection = 'immediate_escalation'
  }
);

-- QueryLeaf provides comprehensive replica set management:
-- 1. SQL-familiar syntax for replica set creation and configuration
-- 2. Advanced health monitoring with comprehensive metrics and alerting
-- 3. Automated failover testing and validation procedures
-- 4. Sophisticated read preference management for performance optimization
-- 5. Comprehensive disaster recovery planning and implementation
-- 6. Real-time monitoring with customizable thresholds and notifications
-- 7. Geographic distribution management for multi-region deployments  
-- 8. Zero-downtime maintenance procedures with automatic validation
-- 9. Performance impact assessment and optimization recommendations
-- 10. Integration with MongoDB's native replica set functionality

Best Practices for Replica Set Implementation

High Availability Design Principles

Essential guidelines for robust MongoDB replica set deployments:

  1. Odd Number of Voting Members: Always maintain an odd number of voting members to prevent split-brain scenarios
  2. Geographic Distribution: Deploy members across multiple availability zones or regions for disaster recovery
  3. Resource Planning: Size replica set members appropriately for expected workload and failover scenarios
  4. Network Optimization: Ensure low-latency, high-bandwidth connections between replica set members
  5. Monitoring Integration: Implement comprehensive monitoring with proactive alerting for health and performance
  6. Regular Testing: Conduct regular failover tests and disaster recovery drills to validate procedures

Operational Excellence

Optimize replica set operations for production environments:

  1. Automated Deployment: Use infrastructure as code for consistent replica set deployments
  2. Configuration Management: Maintain consistent configuration across all replica set members
  3. Security Implementation: Enable authentication, authorization, and encryption for all replica communications
  4. Backup Strategy: Implement multiple backup strategies including hot backups and point-in-time recovery
  5. Performance Monitoring: Track replication lag, network latency, and resource utilization continuously
  6. Documentation Maintenance: Keep runbooks and procedures updated with current configuration and processes

Conclusion

MongoDB's replica set architecture provides comprehensive high availability and disaster recovery capabilities that eliminate the complexity and limitations of traditional database replication systems. The sophisticated election algorithms, automatic failover mechanisms, and flexible configuration options ensure business continuity even during catastrophic failures while maintaining data consistency and application performance.

Key MongoDB Replica Set benefits include:

  • Automatic Failover: Intelligent primary election with no manual intervention required
  • Strong Consistency: Configurable write and read concerns for application-specific consistency requirements
  • Geographic Distribution: Multi-region deployment support for comprehensive disaster recovery
  • Zero Downtime Operations: Add, remove, and maintain replica set members without service interruption
  • Flexible Read Scaling: Advanced read preference configuration for optimal performance distribution
  • Comprehensive Monitoring: Built-in health monitoring with detailed metrics and alerting capabilities

Whether you're building resilient e-commerce platforms, financial applications, or global content delivery systems, MongoDB's replica sets with QueryLeaf's familiar SQL interface provide the foundation for mission-critical high availability infrastructure.

QueryLeaf Integration: QueryLeaf automatically manages MongoDB replica set operations while providing SQL-familiar syntax for replica set creation, health monitoring, and disaster recovery procedures. Advanced high availability patterns, automated failover testing, and comprehensive monitoring are seamlessly handled through familiar SQL constructs, making sophisticated database resilience both powerful and accessible to SQL-oriented operations teams.

The combination of MongoDB's robust replica set capabilities with SQL-style operations makes it an ideal platform for applications requiring both high availability and familiar database management patterns, ensuring your applications maintain continuous operation while remaining manageable as they scale globally.

MongoDB Aggregation Framework Optimization: Advanced Performance Strategies for Complex Data Processing Pipelines

Complex data analysis and processing require sophisticated aggregation capabilities that can handle large datasets efficiently while maintaining query performance and resource optimization. The MongoDB Aggregation Framework provides a powerful pipeline-based approach to data transformation, filtering, grouping, and analysis that scales from simple queries to complex analytical workloads.

MongoDB's aggregation pipeline enables developers to build sophisticated data processing workflows using a series of stages that transform documents as they flow through the pipeline. Unlike traditional SQL aggregation approaches that can become unwieldy for complex operations, MongoDB's stage-based design provides clarity, composability, and optimization opportunities that support both real-time analytics and batch processing scenarios.

The Traditional SQL Aggregation Complexity Challenge

Conventional SQL aggregation approaches often become complex and difficult to optimize for advanced data processing requirements:

-- Traditional PostgreSQL complex aggregation with performance limitations

-- Complex sales analysis requiring multiple subqueries and window functions
WITH regional_sales_base AS (
  SELECT 
    r.region_id,
    r.region_name,
    r.country,
    u.user_id,
    u.email,
    u.created_at as user_registration_date,
    o.order_id,
    o.order_date,
    o.total_amount,
    o.discount_amount,
    o.status as order_status,

    -- Complex date calculations
    EXTRACT(YEAR FROM o.order_date) as order_year,
    EXTRACT(MONTH FROM o.order_date) as order_month,
    EXTRACT(QUARTER FROM o.order_date) as order_quarter,

    -- Category analysis requiring joins
    STRING_AGG(DISTINCT p.category, ', ') as product_categories,
    COUNT(DISTINCT oi.product_id) as unique_products_ordered,
    SUM(oi.quantity) as total_items_ordered,
    AVG(oi.unit_price) as avg_item_price,

    -- Complex business logic calculations
    CASE 
      WHEN o.total_amount > 1000 THEN 'high_value'
      WHEN o.total_amount > 500 THEN 'medium_value'
      ELSE 'low_value'
    END as order_value_category,

    -- Window functions for ranking and comparisons
    ROW_NUMBER() OVER (PARTITION BY r.region_id ORDER BY o.total_amount DESC) as region_order_rank,
    PERCENT_RANK() OVER (PARTITION BY r.region_id ORDER BY o.total_amount) as region_percentile_rank,

    -- Running totals and moving averages
    SUM(o.total_amount) OVER (
      PARTITION BY r.region_id 
      ORDER BY o.order_date 
      ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
    ) as seven_day_rolling_total

  FROM regions r
  INNER JOIN users u ON r.region_id = u.region_id
  INNER JOIN orders o ON u.user_id = o.user_id
  INNER JOIN order_items oi ON o.order_id = oi.order_id
  INNER JOIN products p ON oi.product_id = p.product_id
  WHERE 
    o.order_date >= CURRENT_DATE - INTERVAL '2 years'
    AND o.status IN ('completed', 'shipped', 'delivered')
    AND r.country IN ('US', 'CA', 'UK', 'AU', 'DE')
    AND u.status = 'active'
  GROUP BY 
    r.region_id, r.region_name, r.country, u.user_id, u.email, u.created_at,
    o.order_id, o.order_date, o.total_amount, o.discount_amount, o.status
),

-- Nested aggregation for customer segments
customer_segments AS (
  SELECT 
    user_id,
    email,
    region_name,
    country,

    -- Customer value calculations
    COUNT(DISTINCT order_id) as total_orders,
    SUM(total_amount) as lifetime_value,
    AVG(total_amount) as avg_order_value,
    MAX(order_date) as last_order_date,
    MIN(order_date) as first_order_date,

    -- Time-based analysis
    EXTRACT(DAYS FROM (MAX(order_date) - MIN(order_date))) as customer_tenure_days,
    COUNT(DISTINCT order_year) as active_years,
    COUNT(DISTINCT order_quarter) as active_quarters,

    -- Product diversity analysis
    COUNT(DISTINCT unique_products_ordered) as product_diversity,
    STRING_AGG(DISTINCT product_categories, '; ') as all_categories_purchased,

    -- Value segmentation
    CASE 
      WHEN SUM(total_amount) > 5000 AND COUNT(DISTINCT order_id) > 10 THEN 'vip'
      WHEN SUM(total_amount) > 2000 OR COUNT(DISTINCT order_id) > 15 THEN 'loyal'
      WHEN SUM(total_amount) > 500 OR COUNT(DISTINCT order_id) > 5 THEN 'regular'
      ELSE 'occasional'
    END as customer_segment,

    -- Recency analysis
    CASE 
      WHEN MAX(order_date) >= CURRENT_DATE - INTERVAL '30 days' THEN 'active'
      WHEN MAX(order_date) >= CURRENT_DATE - INTERVAL '90 days' THEN 'recent'
      WHEN MAX(order_date) >= CURRENT_DATE - INTERVAL '180 days' THEN 'dormant'
      ELSE 'inactive'
    END as recency_status

  FROM regional_sales_base
  GROUP BY user_id, email, region_name, country
),

-- Regional performance aggregation
regional_performance AS (
  SELECT 
    region_name,
    country,
    order_year,
    order_quarter,

    -- Volume metrics
    COUNT(DISTINCT user_id) as unique_customers,
    COUNT(DISTINCT order_id) as total_orders,
    SUM(total_amount) as total_revenue,
    SUM(total_items_ordered) as total_items_sold,

    -- Average metrics
    AVG(total_amount) as avg_order_value,
    AVG(avg_item_price) as avg_item_price,

    -- Growth calculations requiring complex window functions
    LAG(SUM(total_amount)) OVER (
      PARTITION BY region_name 
      ORDER BY order_year, order_quarter
    ) as previous_quarter_revenue,

    -- Calculate growth rate
    CASE 
      WHEN LAG(SUM(total_amount)) OVER (
        PARTITION BY region_name 
        ORDER BY order_year, order_quarter
      ) > 0 THEN
        ROUND(
          ((SUM(total_amount) - LAG(SUM(total_amount)) OVER (
            PARTITION BY region_name 
            ORDER BY order_year, order_quarter
          )) / LAG(SUM(total_amount)) OVER (
            PARTITION BY region_name 
            ORDER BY order_year, order_quarter
          ) * 100)::numeric, 2
        )
      ELSE NULL
    END as quarter_over_quarter_growth_pct,

    -- Market share analysis
    SUM(total_amount) / SUM(SUM(total_amount)) OVER (PARTITION BY order_year, order_quarter) * 100 as market_share_pct,

    -- Customer distribution by segment
    COUNT(*) FILTER (WHERE order_value_category = 'high_value') as high_value_orders,
    COUNT(*) FILTER (WHERE order_value_category = 'medium_value') as medium_value_orders,
    COUNT(*) FILTER (WHERE order_value_category = 'low_value') as low_value_orders

  FROM regional_sales_base
  GROUP BY region_name, country, order_year, order_quarter
),

-- Final comprehensive analysis
comprehensive_analysis AS (
  SELECT 
    rp.*,

    -- Customer segment distribution
    cs_stats.vip_customers,
    cs_stats.loyal_customers,
    cs_stats.regular_customers,
    cs_stats.occasional_customers,

    -- Recency analysis
    cs_stats.active_customers,
    cs_stats.recent_customers,
    cs_stats.dormant_customers,
    cs_stats.inactive_customers,

    -- Customer value metrics
    cs_stats.avg_customer_lifetime_value,
    cs_stats.avg_customer_tenure_days,

    -- Performance ranking
    DENSE_RANK() OVER (ORDER BY rp.total_revenue DESC) as revenue_rank,
    DENSE_RANK() OVER (ORDER BY rp.unique_customers DESC) as customer_count_rank,
    DENSE_RANK() OVER (ORDER BY rp.avg_order_value DESC) as aov_rank

  FROM regional_performance rp
  LEFT JOIN (
    SELECT 
      region_name,
      country,
      COUNT(*) FILTER (WHERE customer_segment = 'vip') as vip_customers,
      COUNT(*) FILTER (WHERE customer_segment = 'loyal') as loyal_customers,
      COUNT(*) FILTER (WHERE customer_segment = 'regular') as regular_customers,
      COUNT(*) FILTER (WHERE customer_segment = 'occasional') as occasional_customers,
      COUNT(*) FILTER (WHERE recency_status = 'active') as active_customers,
      COUNT(*) FILTER (WHERE recency_status = 'recent') as recent_customers,
      COUNT(*) FILTER (WHERE recency_status = 'dormant') as dormant_customers,
      COUNT(*) FILTER (WHERE recency_status = 'inactive') as inactive_customers,
      AVG(lifetime_value) as avg_customer_lifetime_value,
      AVG(customer_tenure_days) as avg_customer_tenure_days
    FROM customer_segments
    GROUP BY region_name, country
  ) cs_stats ON rp.region_name = cs_stats.region_name AND rp.country = cs_stats.country
)

SELECT 
  region_name,
  country,
  order_year,
  order_quarter,

  -- Core metrics
  unique_customers,
  total_orders,
  ROUND(total_revenue::numeric, 2) as total_revenue,
  ROUND(avg_order_value::numeric, 2) as avg_order_value,

  -- Growth analysis
  COALESCE(quarter_over_quarter_growth_pct, 0) as growth_rate_pct,
  ROUND(market_share_pct::numeric, 2) as market_share_pct,

  -- Customer segments
  COALESCE(vip_customers, 0) as vip_customers,
  COALESCE(loyal_customers, 0) as loyal_customers,
  COALESCE(regular_customers, 0) as regular_customers,

  -- Customer activity
  COALESCE(active_customers, 0) as active_customers,
  COALESCE(dormant_customers + inactive_customers, 0) as at_risk_customers,

  -- Performance indicators
  revenue_rank,
  customer_count_rank,
  aov_rank,

  -- Composite performance score
  CASE 
    WHEN revenue_rank <= 3 AND customer_count_rank <= 5 AND growth_rate_pct > 10 THEN 'excellent'
    WHEN revenue_rank <= 5 AND growth_rate_pct > 5 THEN 'good'
    WHEN revenue_rank <= 10 OR growth_rate_pct > 0 THEN 'average'
    ELSE 'underperforming'
  END as performance_category,

  -- Strategic recommendations
  CASE 
    WHEN at_risk_customers > active_customers * 0.3 THEN 'Focus on customer retention'
    WHEN growth_rate_pct < 0 THEN 'Investigate declining performance'
    WHEN vip_customers = 0 THEN 'Develop VIP customer programs'
    WHEN market_share_pct < 5 THEN 'Expand market presence'
    ELSE 'Maintain current strategies'
  END as recommended_action

FROM comprehensive_analysis
WHERE order_year >= 2023
ORDER BY 
  order_year DESC, 
  order_quarter DESC, 
  total_revenue DESC
LIMIT 50;

-- Problems with traditional SQL aggregation approaches:
-- 1. Complex nested queries that are difficult to understand and maintain
-- 2. Multiple passes through data requiring expensive joins and subqueries
-- 3. Limited optimization opportunities due to rigid query structure
-- 4. Window functions and CTEs create performance bottlenecks with large datasets
-- 5. Difficult to compose and reuse aggregation logic across different queries
-- 6. Limited support for complex data transformations and conditional logic
-- 7. Poor performance with document-oriented or semi-structured data
-- 8. Inflexible aggregation patterns that don't adapt well to changing requirements
-- 9. Complex indexing requirements that may conflict across different aggregation needs
-- 10. Limited support for hierarchical or nested aggregation patterns

MongoDB Aggregation Framework provides powerful, optimizable pipeline processing:

// MongoDB Aggregation Framework - optimized pipeline processing with advanced strategies
const { MongoClient } = require('mongodb');

const client = new MongoClient('mongodb://localhost:27017');
const db = client.db('ecommerce_analytics_platform');

// Advanced aggregation framework optimization and pipeline management system
class MongoAggregationOptimizer {
  constructor(db) {
    this.db = db;
    this.collections = {
      orders: db.collection('orders'),
      users: db.collection('users'),
      products: db.collection('products'),
      regions: db.collection('regions'),
      analytics: db.collection('analytics_cache')
    };

    this.pipelineCache = new Map();
    this.performanceMetrics = new Map();
    this.optimizationStrategies = {
      earlyFiltering: true,
      indexHints: true,
      stageReordering: true,
      memoryOptimization: true,
      incrementalProcessing: true
    };
  }

  async buildOptimizedSalesAnalysisPipeline(options = {}) {
    console.log('Building optimized sales analysis aggregation pipeline...');

    const {
      dateRange = { start: new Date(Date.now() - 365 * 24 * 60 * 60 * 1000), end: new Date() },
      regions = [],
      includeCustomerSegmentation = true,
      includeProductAnalysis = true,
      includeTemporalAnalysis = true,
      optimizationLevel = 'aggressive'
    } = options;

    // Stage 1: Early filtering for maximum performance (always first)
    const matchStage = {
      $match: {
        order_date: { 
          $gte: dateRange.start, 
          $lte: dateRange.end 
        },
        status: { $in: ['completed', 'shipped', 'delivered'] },
        ...(regions.length > 0 && { 'user.region': { $in: regions } }),
        total_amount: { $gt: 0 } // Exclude zero-value orders early
      }
    };

    // Stage 2: Lookup optimizations with targeted field selection
    const userLookupStage = {
      $lookup: {
        from: 'users',
        localField: 'user_id',
        foreignField: '_id',
        as: 'user_data',
        pipeline: [ // Use pipeline to reduce data transfer
          {
            $match: { 
              status: 'active',
              ...(regions.length > 0 && { region: { $in: regions } })
            }
          },
          {
            $project: {
              _id: 1,
              email: 1,
              region: 1,
              country: 1,
              registration_date: 1,
              customer_segment: 1
            }
          }
        ]
      }
    };

    // Stage 3: Unwind and reshape data efficiently
    const unwindUserStage = { $unwind: '$user_data' };

    // Stage 4: Add computed fields for analysis
    const addFieldsStage = {
      $addFields: {
        // Date calculations optimized for indexing
        order_year: { $year: '$order_date' },
        order_month: { $month: '$order_date' },
        order_quarter: { 
          $ceil: { $divide: [{ $month: '$order_date' }, 3] }
        },
        order_day_of_week: { $dayOfWeek: '$order_date' },

        // Business logic calculations
        order_value_category: {
          $switch: {
            branches: [
              { case: { $gte: ['$total_amount', 1000] }, then: 'high_value' },
              { case: { $gte: ['$total_amount', 500] }, then: 'medium_value' }
            ],
            default: 'low_value'
          }
        },

        // Profit margin calculations
        profit_margin: {
          $multiply: [
            { $divide: [
              { $subtract: ['$total_amount', '$cost_amount'] },
              '$total_amount'
            ]},
            100
          ]
        },

        // Discount analysis
        discount_percentage: {
          $cond: {
            if: { $gt: ['$total_amount', 0] },
            then: { 
              $multiply: [
                { $divide: ['$discount_amount', { $add: ['$total_amount', '$discount_amount'] }] },
                100
              ]
            },
            else: 0
          }
        },

        // Customer tenure at time of order
        customer_tenure_days: {
          $divide: [
            { $subtract: ['$order_date', '$user_data.registration_date'] },
            86400000 // Convert milliseconds to days
          ]
        }
      }
    };

    // Stage 5: Product analysis lookup (conditional)
    const productAnalysisStages = includeProductAnalysis ? [
      {
        $lookup: {
          from: 'order_items',
          localField: '_id',
          foreignField: 'order_id',
          as: 'order_items',
          pipeline: [
            {
              $lookup: {
                from: 'products',
                localField: 'product_id',
                foreignField: '_id',
                as: 'product',
                pipeline: [
                  {
                    $project: {
                      name: 1,
                      category: 1,
                      sub_category: 1,
                      brand: 1,
                      cost_price: 1,
                      margin_percentage: 1
                    }
                  }
                ]
              }
            },
            { $unwind: '$product' },
            {
              $group: {
                _id: '$order_id',
                product_count: { $sum: 1 },
                total_quantity: { $sum: '$quantity' },
                categories: { $addToSet: '$product.category' },
                brands: { $addToSet: '$product.brand' },
                avg_item_margin: { $avg: '$product.margin_percentage' }
              }
            }
          ]
        }
      },
      { $unwind: { path: '$order_items', preserveNullAndEmptyArrays: true } }
    ] : [];

    // Stage 6: Main aggregation pipeline for comprehensive analysis
    const groupingStage = {
      $group: {
        _id: {
          region: '$user_data.region',
          country: '$user_data.country',
          year: '$order_year',
          quarter: '$order_quarter',
          ...(includeTemporalAnalysis && {
            month: '$order_month',
            day_of_week: '$order_day_of_week'
          })
        },

        // Volume metrics
        total_orders: { $sum: 1 },
        unique_customers: { $addToSet: '$user_id' },
        total_revenue: { $sum: '$total_amount' },
        total_items_sold: { $sum: { $ifNull: ['$order_items.total_quantity', 0] } },

        // Value metrics
        avg_order_value: { $avg: '$total_amount' },
        median_order_value: { $median: { input: '$total_amount', method: 'approximate' } },
        max_order_value: { $max: '$total_amount' },
        min_order_value: { $min: '$total_amount' },

        // Profitability metrics
        total_profit: { $sum: { $multiply: ['$total_amount', { $divide: ['$profit_margin', 100] }] } },
        avg_profit_margin: { $avg: '$profit_margin' },

        // Discount analysis
        total_discounts_given: { $sum: '$discount_amount' },
        avg_discount_percentage: { $avg: '$discount_percentage' },
        orders_with_discounts: { 
          $sum: { $cond: [{ $gt: ['$discount_amount', 0] }, 1, 0] }
        },

        // Customer value distribution
        high_value_orders: { 
          $sum: { $cond: [{ $eq: ['$order_value_category', 'high_value'] }, 1, 0] }
        },
        medium_value_orders: {
          $sum: { $cond: [{ $eq: ['$order_value_category', 'medium_value'] }, 1, 0] }
        },
        low_value_orders: {
          $sum: { $cond: [{ $eq: ['$order_value_category', 'low_value'] }, 1, 0] }
        },

        // Product diversity (when product analysis enabled)
        ...(includeProductAnalysis && {
          unique_categories: { $addToSet: '$order_items.categories' },
          unique_brands: { $addToSet: '$order_items.brands' },
          avg_products_per_order: { $avg: '$order_items.product_count' },
          avg_item_margin: { $avg: '$order_items.avg_item_margin' }
        }),

        // Customer tenure analysis
        avg_customer_tenure: { $avg: '$customer_tenure_days' },
        new_customer_orders: {
          $sum: { $cond: [{ $lte: ['$customer_tenure_days', 30] }, 1, 0] }
        },

        // Sample data for detailed analysis
        sample_order_dates: { $push: '$order_date' },
        sample_customer_segments: { $push: '$user_data.customer_segment' }
      }
    };

    // Stage 7: Post-processing calculations
    const postProcessingStage = {
      $addFields: {
        // Customer metrics
        unique_customer_count: { $size: '$unique_customers' },
        orders_per_customer: { 
          $divide: ['$total_orders', { $size: '$unique_customers' }]
        },

        // Revenue per customer
        revenue_per_customer: {
          $divide: ['$total_revenue', { $size: '$unique_customers' }]
        },

        // Profit margins
        profit_margin_percentage: {
          $cond: {
            if: { $gt: ['$total_revenue', 0] },
            then: { $multiply: [{ $divide: ['$total_profit', '$total_revenue'] }, 100] },
            else: 0
          }
        },

        // Discount impact
        discount_rate: {
          $cond: {
            if: { $gt: ['$total_orders', 0] },
            then: { $multiply: [{ $divide: ['$orders_with_discounts', '$total_orders'] }, 100] },
            else: 0
          }
        },

        // Order value distribution
        high_value_percentage: {
          $multiply: [{ $divide: ['$high_value_orders', '$total_orders'] }, 100]
        },

        // New vs returning customer ratio
        new_customer_percentage: {
          $multiply: [{ $divide: ['$new_customer_orders', '$total_orders'] }, 100]
        },

        // Category diversity (when product analysis enabled)
        ...(includeProductAnalysis && {
          category_diversity_score: {
            $size: { $reduce: {
              input: '$unique_categories',
              initialValue: [],
              in: { $setUnion: ['$$value', '$$this'] }
            }}
          }
        }),

        // Performance indicators
        performance_score: {
          $add: [
            { $multiply: [{ $ln: { $add: ['$total_revenue', 1] } }, 0.3] },
            { $multiply: ['$avg_profit_margin', 0.2] },
            { $multiply: [{ $ln: { $add: ['$unique_customer_count', 1] } }, 0.3] },
            { $multiply: ['$orders_per_customer', 0.2] }
          ]
        }
      }
    };

    // Stage 8: Growth analysis using window operations
    const windowAnalysisStage = {
      $setWindowFields: {
        partitionBy: { region: '$_id.region', country: '$_id.country' },
        sortBy: { year: '$_id.year', quarter: '$_id.quarter' },
        output: {
          previous_quarter_revenue: {
            $shift: {
              output: '$total_revenue',
              by: -1
            }
          },
          revenue_trend: {
            $linearFill: '$total_revenue'
          },
          quarter_rank: {
            $rank: {}
          },
          rolling_avg_revenue: {
            $avg: '$total_revenue',
            window: {
              range: [-3, 0],
              unit: 'position'
            }
          }
        }
      }
    };

    // Stage 9: Growth calculations
    const growthCalculationStage = {
      $addFields: {
        quarter_over_quarter_growth: {
          $cond: {
            if: { $and: [
              { $ne: ['$previous_quarter_revenue', null] },
              { $gt: ['$previous_quarter_revenue', 0] }
            ]},
            then: {
              $multiply: [
                { $divide: [
                  { $subtract: ['$total_revenue', '$previous_quarter_revenue'] },
                  '$previous_quarter_revenue'
                ]},
                100
              ]
            },
            else: null
          }
        },

        performance_vs_avg: {
          $multiply: [
            { $divide: [
              { $subtract: ['$total_revenue', '$rolling_avg_revenue'] },
              '$rolling_avg_revenue'
            ]},
            100
          ]
        },

        growth_classification: {
          $switch: {
            branches: [
              { case: { $gte: ['$quarter_over_quarter_growth', 20] }, then: 'high_growth' },
              { case: { $gte: ['$quarter_over_quarter_growth', 10] }, then: 'moderate_growth' },
              { case: { $gte: ['$quarter_over_quarter_growth', 0] }, then: 'stable' },
              { case: { $gte: ['$quarter_over_quarter_growth', -10] }, then: 'declining' }
            ],
            default: 'rapidly_declining'
          }
        }
      }
    };

    // Stage 10: Final projections and cleanup
    const finalProjectionStage = {
      $project: {
        // Location data
        region: '$_id.region',
        country: '$_id.country',
        year: '$_id.year',
        quarter: '$_id.quarter',
        ...(includeTemporalAnalysis && {
          month: '$_id.month',
          day_of_week: '$_id.day_of_week'
        }),

        // Core metrics (rounded for presentation)
        total_orders: 1,
        unique_customer_count: 1,
        total_revenue: { $round: ['$total_revenue', 2] },
        total_profit: { $round: ['$total_profit', 2] },

        // Averages and rates
        avg_order_value: { $round: ['$avg_order_value', 2] },
        median_order_value: { $round: ['$median_order_value', 2] },
        revenue_per_customer: { $round: ['$revenue_per_customer', 2] },
        orders_per_customer: { $round: ['$orders_per_customer', 2] },

        // Percentages
        profit_margin_percentage: { $round: ['$profit_margin_percentage', 2] },
        discount_rate: { $round: ['$discount_rate', 2] },
        high_value_percentage: { $round: ['$high_value_percentage', 2] },
        new_customer_percentage: { $round: ['$new_customer_percentage', 2] },

        // Growth metrics
        quarter_over_quarter_growth: { $round: ['$quarter_over_quarter_growth', 2] },
        performance_vs_avg: { $round: ['$performance_vs_avg', 2] },
        growth_classification: 1,

        // Performance indicators
        performance_score: { $round: ['$performance_score', 2] },
        quarter_rank: 1,

        // Product analysis (conditional)
        ...(includeProductAnalysis && {
          category_diversity_score: 1,
          avg_products_per_order: { $round: ['$avg_products_per_order', 2] },
          avg_item_margin: { $round: ['$avg_item_margin', 2] }
        }),

        // Strategic indicators
        strategic_priority: {
          $switch: {
            branches: [
              { 
                case: { 
                  $and: [
                    { $gte: ['$performance_score', 15] },
                    { $gte: ['$quarter_over_quarter_growth', 10] }
                  ]
                }, 
                then: 'high_potential' 
              },
              { 
                case: { 
                  $and: [
                    { $gte: ['$total_revenue', 50000] },
                    { $gte: ['$profit_margin_percentage', 15] }
                  ]
                }, 
                then: 'cash_cow' 
              },
              { 
                case: { $lte: ['$quarter_over_quarter_growth', -10] }, 
                then: 'needs_attention' 
              }
            ],
            default: 'monitor'
          }
        }
      }
    };

    // Stage 11: Sorting for optimal presentation
    const sortStage = {
      $sort: {
        year: -1,
        quarter: -1,
        total_revenue: -1,
        performance_score: -1
      }
    };

    // Build complete optimized pipeline
    const pipeline = [
      matchStage,
      userLookupStage,
      unwindUserStage,
      addFieldsStage,
      ...productAnalysisStages,
      groupingStage,
      postProcessingStage,
      windowAnalysisStage,
      growthCalculationStage,
      finalProjectionStage,
      sortStage
    ];

    // Add performance optimization hints based on level
    const optimizedPipeline = await this.applyOptimizationStrategies(pipeline, optimizationLevel);

    console.log(`Optimized aggregation pipeline built with ${optimizedPipeline.length} stages`);
    return optimizedPipeline;
  }

  async applyOptimizationStrategies(pipeline, optimizationLevel = 'standard') {
    console.log(`Applying ${optimizationLevel} optimization strategies...`);

    let optimizedPipeline = [...pipeline];

    if (this.optimizationStrategies.earlyFiltering) {
      // Ensure filtering stages are as early as possible
      optimizedPipeline = this.moveFilteringStagesEarly(optimizedPipeline);
    }

    if (this.optimizationStrategies.indexHints) {
      // Add index hints for better query planning
      optimizedPipeline = this.addIndexHints(optimizedPipeline);
    }

    if (this.optimizationStrategies.stageReordering && optimizationLevel === 'aggressive') {
      // Reorder stages for optimal performance
      optimizedPipeline = this.reorderPipelineStages(optimizedPipeline);
    }

    if (this.optimizationStrategies.memoryOptimization) {
      // Add memory usage optimizations
      optimizedPipeline = this.optimizeMemoryUsage(optimizedPipeline);
    }

    return optimizedPipeline;
  }

  moveFilteringStagesEarly(pipeline) {
    const filterStages = [];
    const otherStages = [];

    pipeline.forEach(stage => {
      if (stage.$match) {
        filterStages.push(stage);
      } else {
        otherStages.push(stage);
      }
    });

    return [...filterStages, ...otherStages];
  }

  addIndexHints(pipeline) {
    // Add allowDiskUse and other performance hints
    const firstStage = pipeline[0];

    if (firstStage && firstStage.$match) {
      // Add hint for optimal index usage
      pipeline.unshift({
        $indexStats: {}
      });
    }

    return pipeline;
  }

  optimizeMemoryUsage(pipeline) {
    // Add memory optimization settings
    return pipeline.map(stage => {
      if (stage.$group || stage.$sort) {
        return {
          ...stage,
          allowDiskUse: true
        };
      }
      return stage;
    });
  }

  async executeOptimizedAggregation(pipeline, options = {}) {
    console.log('Executing optimized aggregation pipeline...');

    const {
      collection = 'orders',
      explain = false,
      allowDiskUse = true,
      maxTimeMS = 300000, // 5 minutes
      batchSize = 1000
    } = options;

    const targetCollection = this.collections[collection];
    const startTime = Date.now();

    try {
      if (explain) {
        // Return execution plan for analysis
        const explainResult = await targetCollection.aggregate(pipeline).explain('executionStats');
        return {
          success: true,
          explain: explainResult,
          executionTimeMs: Date.now() - startTime
        };
      }

      // Execute aggregation with options
      const cursor = targetCollection.aggregate(pipeline, {
        allowDiskUse,
        maxTimeMS,
        batchSize,
        comment: `Optimized aggregation - ${new Date().toISOString()}`
      });

      const results = await cursor.toArray();
      const executionTime = Date.now() - startTime;

      // Cache pipeline performance metrics
      const pipelineHash = this.generatePipelineHash(pipeline);
      this.performanceMetrics.set(pipelineHash, {
        executionTimeMs: executionTime,
        resultCount: results.length,
        timestamp: new Date(),
        collection: collection
      });

      console.log(`Aggregation completed in ${executionTime}ms, returned ${results.length} documents`);

      return {
        success: true,
        results: results,
        executionTimeMs: executionTime,
        resultCount: results.length,
        pipelineHash: pipelineHash
      };

    } catch (error) {
      console.error('Aggregation execution failed:', error);
      return {
        success: false,
        error: error.message,
        executionTimeMs: Date.now() - startTime
      };
    }
  }

  async buildCustomerSegmentationPipeline(options = {}) {
    console.log('Building advanced customer segmentation pipeline...');

    const {
      lookbackMonths = 12,
      includeProductAffinity = true,
      includeGeographicAnalysis = true,
      segmentationModel = 'rfm' // recency, frequency, monetary
    } = options;

    const lookbackDate = new Date();
    lookbackDate.setMonth(lookbackDate.getMonth() - lookbackMonths);

    const pipeline = [
      // Stage 1: Filter active users and recent data
      {
        $match: {
          status: 'active',
          created_at: { $lte: new Date() },
          deleted_at: { $exists: false }
        }
      },

      // Stage 2: Join with order data
      {
        $lookup: {
          from: 'orders',
          localField: '_id',
          foreignField: 'user_id',
          as: 'orders',
          pipeline: [
            {
              $match: {
                order_date: { $gte: lookbackDate },
                status: { $in: ['completed', 'shipped', 'delivered'] },
                total_amount: { $gt: 0 }
              }
            },
            {
              $project: {
                order_date: 1,
                total_amount: 1,
                discount_amount: 1,
                items: 1,
                product_categories: 1
              }
            }
          ]
        }
      },

      // Stage 3: Calculate RFM metrics
      {
        $addFields: {
          // Recency: Days since last purchase
          recency_days: {
            $cond: {
              if: { $gt: [{ $size: '$orders' }, 0] },
              then: {
                $divide: [
                  { $subtract: [
                    new Date(),
                    { $max: '$orders.order_date' }
                  ]},
                  86400000 // Convert to days
                ]
              },
              else: 9999 // Very high number for users with no orders
            }
          },

          // Frequency: Number of orders
          frequency: { $size: '$orders' },

          // Monetary: Total amount spent
          monetary_value: { $sum: '$orders.total_amount' },

          // Additional metrics
          avg_order_value: { $avg: '$orders.total_amount' },
          total_discount_used: { $sum: '$orders.discount_amount' },
          order_date_range: {
            $cond: {
              if: { $gt: [{ $size: '$orders' }, 0] },
              then: {
                $divide: [
                  { $subtract: [
                    { $max: '$orders.order_date' },
                    { $min: '$orders.order_date' }
                  ]},
                  86400000
                ]
              },
              else: 0
            }
          }
        }
      },

      // Stage 4: Product affinity analysis (conditional)
      ...(includeProductAffinity ? [
        {
          $addFields: {
            product_categories: {
              $reduce: {
                input: '$orders.product_categories',
                initialValue: [],
                in: { $setUnion: ['$$value', '$$this'] }
              }
            },
            category_diversity: {
              $size: {
                $reduce: {
                  input: '$orders.product_categories',
                  initialValue: [],
                  in: { $setUnion: ['$$value', '$$this'] }
                }
              }
            }
          }
        }
      ] : []),

      // Stage 5: Calculate percentiles for RFM scoring
      {
        $setWindowFields: {
          sortBy: { recency_days: 1 },
          output: {
            recency_percentile: {
              $percentRank: {
                input: '$recency_days',
                range: [0, 1]
              }
            }
          }
        }
      },
      {
        $setWindowFields: {
          sortBy: { frequency: 1 },
          output: {
            frequency_percentile: {
              $percentRank: {
                input: '$frequency',
                range: [0, 1]
              }
            }
          }
        }
      },
      {
        $setWindowFields: {
          sortBy: { monetary_value: 1 },
          output: {
            monetary_percentile: {
              $percentRank: {
                input: '$monetary_value',
                range: [0, 1]
              }
            }
          }
        }
      },

      // Stage 6: Calculate RFM scores
      {
        $addFields: {
          // Invert recency score (lower days = higher score)
          recency_score: {
            $ceil: { $multiply: [{ $subtract: [1, '$recency_percentile'] }, 5] }
          },
          frequency_score: {
            $ceil: { $multiply: ['$frequency_percentile', 5] }
          },
          monetary_score: {
            $ceil: { $multiply: ['$monetary_percentile', 5] }
          }
        }
      },

      // Stage 7: Generate customer segments
      {
        $addFields: {
          rfm_score: {
            $concat: [
              { $toString: '$recency_score' },
              { $toString: '$frequency_score' },
              { $toString: '$monetary_score' }
            ]
          },

          // Comprehensive customer segment classification
          customer_segment: {
            $switch: {
              branches: [
                {
                  case: {
                    $and: [
                      { $gte: ['$recency_score', 4] },
                      { $gte: ['$frequency_score', 4] },
                      { $gte: ['$monetary_score', 4] }
                    ]
                  },
                  then: 'champions'
                },
                {
                  case: {
                    $and: [
                      { $gte: ['$recency_score', 3] },
                      { $gte: ['$frequency_score', 3] },
                      { $gte: ['$monetary_score', 4] }
                    ]
                  },
                  then: 'loyal_customers'
                },
                {
                  case: {
                    $and: [
                      { $gte: ['$recency_score', 4] },
                      { $lte: ['$frequency_score', 2] },
                      { $gte: ['$monetary_score', 3] }
                    ]
                  },
                  then: 'potential_loyalists'
                },
                {
                  case: {
                    $and: [
                      { $gte: ['$recency_score', 4] },
                      { $lte: ['$frequency_score', 1] },
                      { $lte: ['$monetary_score', 2] }
                    ]
                  },
                  then: 'new_customers'
                },
                {
                  case: {
                    $and: [
                      { $lte: ['$recency_score', 2] },
                      { $gte: ['$frequency_score', 3] },
                      { $gte: ['$monetary_score', 3] }
                    ]
                  },
                  then: 'at_risk'
                },
                {
                  case: {
                    $and: [
                      { $lte: ['$recency_score', 2] },
                      { $lte: ['$frequency_score', 2] },
                      { $gte: ['$monetary_score', 3] }
                    ]
                  },
                  then: 'cannot_lose_them'
                },
                {
                  case: {
                    $and: [
                      { $lte: ['$recency_score', 2] },
                      { $lte: ['$frequency_score', 2] },
                      { $lte: ['$monetary_score', 2] }
                    ]
                  },
                  then: 'hibernating'
                }
              ],
              default: 'promising'
            }
          },

          // Customer lifetime value prediction
          predicted_clv: {
            $multiply: [
              '$avg_order_value',
              '$frequency',
              { $divide: ['$order_date_range', 365] }, // Annualized frequency
              { $subtract: [5, { $divide: ['$recency_days', 73] }] } // Recency factor
            ]
          },

          // Churn risk score
          churn_risk_score: {
            $cond: {
              if: { $gt: ['$recency_days', 90] },
              then: {
                $add: [
                  { $multiply: ['$recency_days', 0.01] },
                  { $multiply: [{ $subtract: [5, '$frequency_score'] }, 0.2] }
                ]
              },
              else: 0.1
            }
          }
        }
      },

      // Stage 8: Final projection with insights
      {
        $project: {
          _id: 1,
          email: 1,
          region: 1,
          country: 1,
          registration_date: 1,

          // RFM metrics
          recency_days: { $round: ['$recency_days', 0] },
          frequency: 1,
          monetary_value: { $round: ['$monetary_value', 2] },
          avg_order_value: { $round: ['$avg_order_value', 2] },

          // RFM scores
          recency_score: 1,
          frequency_score: 1,
          monetary_score: 1,
          rfm_score: 1,

          // Segmentation
          customer_segment: 1,
          predicted_clv: { $round: ['$predicted_clv', 2] },
          churn_risk_score: { $round: ['$churn_risk_score', 2] },

          // Additional insights
          ...(includeProductAffinity && {
            category_diversity: 1,
            preferred_categories: '$product_categories'
          }),

          // Actionable recommendations
          recommended_action: {
            $switch: {
              branches: [
                { case: { $eq: ['$customer_segment', 'champions'] }, then: 'Reward and upsell' },
                { case: { $eq: ['$customer_segment', 'loyal_customers'] }, then: 'Maintain engagement' },
                { case: { $eq: ['$customer_segment', 'potential_loyalists'] }, then: 'Increase frequency' },
                { case: { $eq: ['$customer_segment', 'new_customers'] }, then: 'Onboarding focus' },
                { case: { $eq: ['$customer_segment', 'at_risk'] }, then: 'Re-engagement campaign' },
                { case: { $eq: ['$customer_segment', 'cannot_lose_them'] }, then: 'Win-back strategy' },
                { case: { $eq: ['$customer_segment', 'hibernating'] }, then: 'Reactivation offer' }
              ],
              default: 'General nurturing'
            }
          }
        }
      },

      // Stage 9: Sort by value for prioritization
      {
        $sort: {
          customer_segment: 1,
          predicted_clv: -1,
          monetary_value: -1
        }
      }
    ];

    console.log('Customer segmentation pipeline built successfully');
    return pipeline;
  }

  async performPipelineBenchmarking(pipelines, options = {}) {
    console.log('Performing comprehensive pipeline benchmarking...');

    const {
      iterations = 3,
      includeExplainPlans = true,
      warmupRuns = 1
    } = options;

    const benchmarkResults = [];

    for (const [pipelineName, pipeline] of Object.entries(pipelines)) {
      console.log(`Benchmarking pipeline: ${pipelineName}`);

      const pipelineResults = {
        name: pipelineName,
        stages: pipeline.length,
        iterations: [],
        avgExecutionTime: 0,
        minExecutionTime: Infinity,
        maxExecutionTime: 0,
        explainPlan: null
      };

      // Warmup runs
      for (let w = 0; w < warmupRuns; w++) {
        await this.executeOptimizedAggregation(pipeline, { collection: 'orders' });
      }

      // Benchmark iterations
      for (let i = 0; i < iterations; i++) {
        const result = await this.executeOptimizedAggregation(pipeline, { 
          collection: 'orders',
          explain: i === 0 && includeExplainPlans
        });

        if (result.success) {
          if (result.explain) {
            pipelineResults.explainPlan = result.explain;
          }

          if (result.executionTimeMs) {
            pipelineResults.iterations.push(result.executionTimeMs);
            pipelineResults.minExecutionTime = Math.min(pipelineResults.minExecutionTime, result.executionTimeMs);
            pipelineResults.maxExecutionTime = Math.max(pipelineResults.maxExecutionTime, result.executionTimeMs);
          }
        }
      }

      // Calculate averages
      if (pipelineResults.iterations.length > 0) {
        pipelineResults.avgExecutionTime = pipelineResults.iterations.reduce((sum, time) => sum + time, 0) / pipelineResults.iterations.length;
      }

      benchmarkResults.push(pipelineResults);
    }

    // Sort by performance
    benchmarkResults.sort((a, b) => a.avgExecutionTime - b.avgExecutionTime);

    console.log('Pipeline benchmarking completed');
    return benchmarkResults;
  }

  generatePipelineHash(pipeline) {
    const pipelineString = JSON.stringify(pipeline, Object.keys(pipeline).sort());
    return require('crypto').createHash('md5').update(pipelineString).digest('hex');
  }

  async createOptimalIndexes() {
    console.log('Creating optimal indexes for aggregation performance...');

    const orders = this.collections.orders;
    const users = this.collections.users;

    try {
      // Compound indexes for common aggregation patterns
      await orders.createIndex({ 
        order_date: -1, 
        status: 1, 
        user_id: 1 
      }, { background: true });

      await orders.createIndex({ 
        user_id: 1, 
        order_date: -1, 
        total_amount: -1 
      }, { background: true });

      await orders.createIndex({ 
        status: 1, 
        order_date: -1 
      }, { background: true });

      await users.createIndex({ 
        status: 1, 
        region: 1, 
        created_at: -1 
      }, { background: true });

      console.log('Optimal indexes created successfully');
    } catch (error) {
      console.warn('Index creation warning:', error.message);
    }
  }
}

// Benefits of MongoDB Aggregation Framework Optimization:
// - Pipeline-based design enables clear, composable data transformations
// - Automatic query optimization and index utilization across pipeline stages  
// - Memory and performance optimizations with allowDiskUse and stage reordering
// - Advanced window functions and statistical operations for complex analysis
// - Flexible stage composition that adapts to changing analytical requirements
// - Integration with MongoDB's distributed architecture for horizontal scaling
// - Real-time and batch processing capabilities with consistent optimization patterns
// - Rich data transformation functions supporting nested documents and arrays
// - Performance monitoring and explain plan analysis for continuous optimization
// - SQL-compatible aggregation patterns through QueryLeaf integration

module.exports = {
  MongoAggregationOptimizer
};

Understanding MongoDB Aggregation Framework Architecture

Advanced Pipeline Optimization Strategies and Performance Tuning

Implement sophisticated aggregation optimization patterns for production-scale analytics:

// Advanced aggregation optimization patterns and performance monitoring
class ProductionAggregationManager {
  constructor(db) {
    this.db = db;
    this.pipelineLibrary = new Map();
    this.performanceBaselines = new Map();
    this.optimizationRules = [
      'early_filtering',
      'index_utilization', 
      'memory_optimization',
      'stage_reordering',
      'parallel_processing'
    ];
  }

  async buildRealtimeAnalyticsPipeline(analyticsConfig) {
    console.log('Building real-time analytics aggregation pipeline...');

    const {
      timeWindow = '1h',
      updateInterval = '5m',
      includeTrends = true,
      includeAnomalyDetection = true,
      alertThresholds = {}
    } = analyticsConfig;

    // Real-time metrics pipeline with change stream integration
    const realtimePipeline = [
      {
        $match: {
          operationType: { $in: ['insert', 'update'] },
          'fullDocument.order_date': {
            $gte: new Date(Date.now() - this.parseTimeWindow(timeWindow))
          },
          'fullDocument.status': { $in: ['completed', 'shipped', 'delivered'] }
        }
      },

      {
        $replaceRoot: {
          newRoot: '$fullDocument'
        }
      },

      {
        $group: {
          _id: {
            $dateTrunc: {
              date: '$order_date',
              unit: 'minute',
              binSize: parseInt(updateInterval)
            }
          },

          // Real-time metrics
          order_count: { $sum: 1 },
          revenue: { $sum: '$total_amount' },
          avg_order_value: { $avg: '$total_amount' },
          unique_customers: { $addToSet: '$user_id' },

          // Geographic distribution
          regions: { $addToSet: '$region' },
          countries: { $addToSet: '$country' },

          // Product performance
          product_categories: { $push: '$product_categories' },

          // Anomaly detection data points
          revenue_samples: { $push: '$total_amount' },
          order_timestamps: { $push: '$order_date' }
        }
      },

      {
        $addFields: {
          time_bucket: '$_id',
          unique_customer_count: { $size: '$unique_customers' },
          region_diversity: { $size: '$regions' },

          // Statistical measures for anomaly detection
          revenue_std: { $stdDevPop: '$revenue_samples' },
          revenue_median: { $median: { input: '$revenue_samples', method: 'approximate' } },

          // Performance indicators
          orders_per_minute: { 
            $divide: ['$order_count', parseInt(updateInterval)]
          },
          revenue_per_minute: {
            $divide: ['$revenue', parseInt(updateInterval)]
          }
        }
      },

      // Trend analysis using window operations
      {
        $setWindowFields: {
          sortBy: { time_bucket: 1 },
          output: {
            revenue_trend: {
              $linearFill: '$revenue'
            },
            moving_avg_revenue: {
              $avg: '$revenue',
              window: {
                range: [-6, 0], // 7-period moving average
                unit: 'position'
              }
            },
            revenue_change: {
              $subtract: [
                '$revenue',
                {
                  $shift: {
                    output: '$revenue',
                    by: -1
                  }
                }
              ]
            }
          }
        }
      },

      // Anomaly detection
      ...(includeAnomalyDetection ? [
        {
          $addFields: {
            anomaly_score: {
              $abs: {
                $divide: [
                  { $subtract: ['$revenue', '$moving_avg_revenue'] },
                  { $add: ['$revenue_std', 1] }
                ]
              }
            },

            is_anomaly: {
              $gt: [
                {
                  $abs: {
                    $divide: [
                      { $subtract: ['$revenue', '$moving_avg_revenue'] },
                      { $add: ['$revenue_std', 1] }
                    ]
                  }
                },
                2 // 2 standard deviations
              ]
            },

            performance_alert: {
              $cond: {
                if: {
                  $or: [
                    { $lt: ['$revenue', alertThresholds.minRevenue || 0] },
                    { $gt: ['$orders_per_minute', alertThresholds.maxOrderRate || 1000] },
                    { $lt: ['$avg_order_value', alertThresholds.minAOV || 0] }
                  ]
                },
                then: true,
                else: false
              }
            }
          }
        }
      ] : []),

      {
        $project: {
          time_bucket: 1,
          order_count: 1,
          revenue: { $round: ['$revenue', 2] },
          avg_order_value: { $round: ['$avg_order_value', 2] },
          unique_customer_count: 1,
          region_diversity: 1,

          // Trend indicators
          ...(includeTrends && {
            revenue_change: { $round: ['$revenue_change', 2] },
            moving_avg_revenue: { $round: ['$moving_avg_revenue', 2] },
            trend_direction: {
              $switch: {
                branches: [
                  { case: { $gt: ['$revenue_change', 0] }, then: 'up' },
                  { case: { $lt: ['$revenue_change', 0] }, then: 'down' }
                ],
                default: 'stable'
              }
            }
          }),

          // Alert information
          ...(includeAnomalyDetection && {
            anomaly_score: { $round: ['$anomaly_score', 3] },
            is_anomaly: 1,
            performance_alert: 1
          }),

          // Timestamp for real-time tracking
          computed_at: new Date()
        }
      },

      {
        $sort: { time_bucket: -1 }
      },

      {
        $limit: 100 // Keep recent data points
      }
    ];

    return realtimePipeline;
  }

  async optimizePipelineForScale(pipeline, scaleRequirements) {
    console.log('Optimizing pipeline for scale requirements...');

    const {
      expectedDocuments = 1000000,
      maxExecutionTime = 60000,
      memoryLimit = '100M',
      parallelization = true
    } = scaleRequirements;

    let optimizedPipeline = [...pipeline];

    // 1. Add early filtering based on data volume
    if (expectedDocuments > 100000) {
      optimizedPipeline = this.addEarlyFiltering(optimizedPipeline);
    }

    // 2. Optimize grouping operations for large datasets
    optimizedPipeline = this.optimizeGroupingStages(optimizedPipeline, expectedDocuments);

    // 3. Add memory management directives
    optimizedPipeline = this.addMemoryManagement(optimizedPipeline, memoryLimit);

    // 4. Enable parallelization where possible
    if (parallelization) {
      optimizedPipeline = this.enableParallelProcessing(optimizedPipeline);
    }

    // 5. Add performance monitoring
    optimizedPipeline = this.addPerformanceMonitoring(optimizedPipeline);

    return optimizedPipeline;
  }

  addEarlyFiltering(pipeline) {
    // Move all $match stages to the beginning
    const matchStages = pipeline.filter(stage => stage.$match);
    const otherStages = pipeline.filter(stage => !stage.$match);

    return [...matchStages, ...otherStages];
  }

  optimizeGroupingStages(pipeline, expectedDocuments) {
    return pipeline.map(stage => {
      if (stage.$group && expectedDocuments > 500000) {
        return {
          ...stage,
          allowDiskUse: true,
          // Use approximate algorithms for large datasets
          ...(stage.$group.$median && {
            $group: {
              ...stage.$group,
              $median: {
                ...stage.$group.$median,
                method: 'approximate'
              }
            }
          })
        };
      }
      return stage;
    });
  }

  addMemoryManagement(pipeline, memoryLimit) {
    return pipeline.map((stage, index) => {
      // Add memory management for memory-intensive stages
      if (stage.$sort || stage.$group || stage.$bucket) {
        return {
          ...stage,
          allowDiskUse: true,
          maxMemoryUsageBytes: this.parseMemoryLimit(memoryLimit)
        };
      }
      return stage;
    });
  }

  parseMemoryLimit(limit) {
    const units = { M: 1024 * 1024, G: 1024 * 1024 * 1024 };
    const match = limit.match(/(\d+)([MG])/);
    return match ? parseInt(match[1]) * units[match[2]] : 100 * 1024 * 1024;
  }

  parseTimeWindow(timeWindow) {
    const units = { m: 60000, h: 3600000, d: 86400000 };
    const match = timeWindow.match(/(\d+)([mhd])/);
    return match ? parseInt(match[1]) * units[match[2]] : 3600000;
  }
}

SQL-Style Aggregation Optimization with QueryLeaf

QueryLeaf provides familiar SQL syntax for MongoDB aggregation optimization and complex analytics:

-- QueryLeaf aggregation framework optimization with SQL-familiar patterns

-- Advanced sales analysis with optimized aggregation pipeline
WITH regional_sales_optimized AS (
  SELECT 
    region,
    country,
    YEAR(order_date) as order_year,
    QUARTER(order_date) as order_quarter,
    MONTH(order_date) as order_month,

    -- Optimized aggregation functions
    COUNT(*) as total_orders,
    COUNT(DISTINCT user_id) as unique_customers,
    SUM(total_amount) as total_revenue,
    AVG(total_amount) as avg_order_value,
    MEDIAN_APPROX(total_amount) as median_order_value,
    STDDEV(total_amount) as revenue_stddev,

    -- Advanced statistical functions
    PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY total_amount) as q1_order_value,
    PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY total_amount) as q3_order_value,
    PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY total_amount) as p95_order_value,

    -- Product diversity metrics
    COUNT(DISTINCT UNNEST(product_categories)) as unique_categories,
    AVG(ARRAY_LENGTH(product_categories)) as avg_categories_per_order,

    -- Customer behavior analysis
    COUNT(*) FILTER (WHERE total_amount > 1000) as high_value_orders,
    COUNT(*) FILTER (WHERE discount_amount > 0) as discounted_orders,
    AVG(discount_amount) as avg_discount,

    -- Time-based patterns
    COUNT(*) FILTER (WHERE EXTRACT(DOW FROM order_date) IN (0, 6)) as weekend_orders,
    COUNT(*) FILTER (WHERE EXTRACT(HOUR FROM order_date) BETWEEN 9 AND 17) as business_hours_orders,

    -- Customer tenure analysis
    AVG(EXTRACT(DAYS FROM order_date - user_registration_date)) as avg_customer_tenure,

    -- Seasonal indicators
    CASE 
      WHEN MONTH(order_date) IN (12, 1, 2) THEN 'winter'
      WHEN MONTH(order_date) IN (3, 4, 5) THEN 'spring'
      WHEN MONTH(order_date) IN (6, 7, 8) THEN 'summer'
      ELSE 'fall'
    END as season

  FROM orders o
  INNER JOIN users u ON o.user_id = u._id
  WHERE o.order_date >= CURRENT_DATE - INTERVAL '2 years'
    AND o.status IN ('completed', 'shipped', 'delivered')
    AND o.total_amount > 0
    AND u.status = 'active'
  GROUP BY region, country, order_year, order_quarter, order_month

  -- QueryLeaf optimization hints
  USING INDEX (order_date_status_user_idx)
  WITH AGGREGATION_OPTIONS (
    allow_disk_use = true,
    max_memory_usage = '200M',
    optimization_level = 'aggressive'
  )
),

-- Window functions for trend analysis and growth calculations
growth_analysis AS (
  SELECT 
    *,

    -- Period-over-period growth calculations
    LAG(total_revenue) OVER (
      PARTITION BY region, country 
      ORDER BY order_year, order_quarter, order_month
    ) as previous_period_revenue,

    LAG(unique_customers) OVER (
      PARTITION BY region, country
      ORDER BY order_year, order_quarter, order_month  
    ) as previous_period_customers,

    -- Moving averages for trend smoothing
    AVG(total_revenue) OVER (
      PARTITION BY region, country
      ORDER BY order_year, order_quarter, order_month
      ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
    ) as three_period_avg_revenue,

    AVG(avg_order_value) OVER (
      PARTITION BY region, country
      ORDER BY order_year, order_quarter, order_month
      ROWS BETWEEN 5 PRECEDING AND CURRENT ROW  
    ) as six_period_avg_aov,

    -- Rank and percentile calculations
    RANK() OVER (
      PARTITION BY order_year, order_quarter
      ORDER BY total_revenue DESC
    ) as revenue_rank,

    PERCENT_RANK() OVER (
      PARTITION BY order_year, order_quarter
      ORDER BY total_revenue
    ) as revenue_percentile,

    -- Running totals and cumulative metrics
    SUM(total_revenue) OVER (
      PARTITION BY region, country, order_year
      ORDER BY order_quarter, order_month
      ROWS UNBOUNDED PRECEDING
    ) as ytd_revenue,

    -- Anomaly detection using statistical functions
    ABS(total_revenue - AVG(total_revenue) OVER (
      PARTITION BY region, country
      ORDER BY order_year, order_quarter, order_month
      ROWS BETWEEN 11 PRECEDING AND CURRENT ROW
    )) / STDDEV(total_revenue) OVER (
      PARTITION BY region, country  
      ORDER BY order_year, order_quarter, order_month
      ROWS BETWEEN 11 PRECEDING AND CURRENT ROW
    ) as revenue_z_score

  FROM regional_sales_optimized
),

-- Customer segmentation using advanced analytics
customer_segmentation AS (
  SELECT 
    user_id,
    region,
    country,
    registration_date,

    -- RFM analysis (Recency, Frequency, Monetary)
    EXTRACT(DAYS FROM CURRENT_DATE - MAX(order_date)) as recency_days,
    COUNT(*) as frequency,
    SUM(total_amount) as monetary_value,
    AVG(total_amount) as avg_order_value,

    -- Advanced customer metrics
    MAX(order_date) - MIN(order_date) as customer_lifespan,
    COUNT(DISTINCT EXTRACT(QUARTER FROM order_date)) as active_quarters,
    STDDEV(total_amount) as order_consistency,

    -- Product affinity analysis
    COUNT(DISTINCT UNNEST(product_categories)) as category_diversity,
    MODE() WITHIN GROUP (ORDER BY UNNEST(product_categories)) as preferred_category,

    -- Seasonal behavior patterns
    AVG(total_amount) FILTER (WHERE season = 'winter') as winter_avg_spend,
    AVG(total_amount) FILTER (WHERE season = 'summer') as summer_avg_spend,

    -- Channel preference analysis  
    COUNT(*) FILTER (WHERE channel = 'mobile') as mobile_orders,
    COUNT(*) FILTER (WHERE channel = 'web') as web_orders,
    COUNT(*) FILTER (WHERE channel = 'store') as store_orders,

    -- Time-based behavior patterns
    AVG(EXTRACT(HOUR FROM order_timestamp)) as preferred_hour,
    COUNT(*) FILTER (WHERE EXTRACT(DOW FROM order_date) IN (0, 6)) / COUNT(*)::float as weekend_preference,

    -- Discount utilization patterns
    COUNT(*) FILTER (WHERE discount_amount > 0) / COUNT(*)::float as discount_utilization_rate,
    AVG(discount_amount) FILTER (WHERE discount_amount > 0) as avg_discount_when_used

  FROM orders o
  INNER JOIN users u ON o.user_id = u._id
  WHERE o.order_date >= CURRENT_DATE - INTERVAL '1 year'
    AND o.status IN ('completed', 'shipped', 'delivered')
    AND u.status = 'active'
  GROUP BY user_id, region, country, registration_date
),

-- RFM scoring and segmentation
customer_segments_scored AS (
  SELECT 
    *,

    -- RFM quintile scoring (1-5 scale)
    NTILE(5) OVER (ORDER BY recency_days DESC) as recency_score, -- Lower recency = higher score
    NTILE(5) OVER (ORDER BY frequency ASC) as frequency_score,
    NTILE(5) OVER (ORDER BY monetary_value ASC) as monetary_score,

    -- Comprehensive customer segment classification
    CASE 
      WHEN NTILE(5) OVER (ORDER BY recency_days DESC) >= 4 
           AND NTILE(5) OVER (ORDER BY frequency ASC) >= 4 
           AND NTILE(5) OVER (ORDER BY monetary_value ASC) >= 4 THEN 'champions'
      WHEN NTILE(5) OVER (ORDER BY recency_days DESC) >= 4 
           AND NTILE(5) OVER (ORDER BY frequency ASC) >= 3 
           AND NTILE(5) OVER (ORDER BY monetary_value ASC) >= 3 THEN 'loyal_customers'  
      WHEN NTILE(5) OVER (ORDER BY recency_days DESC) >= 4 
           AND NTILE(5) OVER (ORDER BY frequency ASC) <= 2 
           AND NTILE(5) OVER (ORDER BY monetary_value ASC) >= 3 THEN 'potential_loyalists'
      WHEN NTILE(5) OVER (ORDER BY recency_days DESC) >= 4 
           AND NTILE(5) OVER (ORDER BY frequency ASC) <= 1 THEN 'new_customers'
      WHEN NTILE(5) OVER (ORDER BY recency_days DESC) BETWEEN 2 AND 3 
           AND NTILE(5) OVER (ORDER BY frequency ASC) >= 3 THEN 'at_risk'
      WHEN NTILE(5) OVER (ORDER BY recency_days DESC) <= 2 
           AND NTILE(5) OVER (ORDER BY frequency ASC) >= 3 
           AND NTILE(5) OVER (ORDER BY monetary_value ASC) >= 3 THEN 'cannot_lose_them'
      WHEN NTILE(5) OVER (ORDER BY recency_days DESC) <= 2 
           AND NTILE(5) OVER (ORDER BY frequency ASC) <= 2 THEN 'hibernating'
      ELSE 'promising'
    END as customer_segment,

    -- Customer Lifetime Value prediction
    (avg_order_value * frequency * 
     CASE WHEN customer_lifespan > 0 THEN 365.0 / EXTRACT(DAYS FROM customer_lifespan) ELSE 12 END *
     (6 - LEAST(5, recency_days / 30.0))) as predicted_clv,

    -- Churn risk assessment
    CASE 
      WHEN recency_days > 180 THEN 'high_risk'
      WHEN recency_days > 90 THEN 'medium_risk'
      WHEN recency_days > 30 THEN 'low_risk'
      ELSE 'active'
    END as churn_risk,

    -- Channel preference classification
    CASE 
      WHEN mobile_orders > web_orders AND mobile_orders > store_orders THEN 'mobile_first'
      WHEN web_orders > mobile_orders AND web_orders > store_orders THEN 'web_first' 
      WHEN store_orders > mobile_orders AND store_orders > web_orders THEN 'store_first'
      ELSE 'omnichannel'
    END as channel_preference

  FROM customer_segmentation
),

-- Comprehensive business intelligence summary
business_intelligence_summary AS (
  SELECT 
    ga.region,
    ga.country,
    ga.order_year,
    ga.order_quarter,

    -- Performance metrics with growth indicators
    ga.total_revenue,
    ga.unique_customers,
    ga.avg_order_value,

    -- Growth calculations
    CASE 
      WHEN ga.previous_period_revenue > 0 THEN
        ROUND(((ga.total_revenue - ga.previous_period_revenue) / ga.previous_period_revenue * 100)::numeric, 2)
      ELSE NULL
    END as revenue_growth_pct,

    CASE
      WHEN ga.previous_period_customers > 0 THEN
        ROUND(((ga.unique_customers - ga.previous_period_customers) / ga.previous_period_customers * 100)::numeric, 2) 
      ELSE NULL
    END as customer_growth_pct,

    -- Trend indicators
    CASE 
      WHEN ga.total_revenue > ga.three_period_avg_revenue * 1.1 THEN 'growing'
      WHEN ga.total_revenue < ga.three_period_avg_revenue * 0.9 THEN 'declining'
      ELSE 'stable'
    END as revenue_trend,

    -- Performance rankings
    ga.revenue_rank,
    ga.revenue_percentile,

    -- Anomaly detection
    CASE 
      WHEN ga.revenue_z_score > 2 THEN 'positive_anomaly'
      WHEN ga.revenue_z_score < -2 THEN 'negative_anomaly'
      ELSE 'normal'
    END as anomaly_status,

    -- Customer segment distribution
    css.champions_count,
    css.loyal_customers_count,
    css.at_risk_count,
    css.hibernating_count,

    -- Customer value metrics
    css.avg_predicted_clv,
    css.high_risk_customers,

    -- Channel distribution
    css.mobile_first_customers,
    css.web_first_customers,
    css.omnichannel_customers,

    -- Strategic recommendations
    CASE 
      WHEN ga.revenue_growth_pct < -10 AND css.at_risk_count > css.loyal_customers_count THEN 'urgent_retention_focus'
      WHEN ga.revenue_growth_pct > 20 AND ga.revenue_rank <= 5 THEN 'scale_and_expand'
      WHEN css.hibernating_count > css.champions_count THEN 'reactivation_campaign'  
      WHEN ga.avg_order_value < ga.six_period_avg_aov * 0.9 THEN 'upselling_opportunity'
      ELSE 'maintain_momentum'
    END as strategic_recommendation

  FROM growth_analysis ga
  LEFT JOIN (
    SELECT 
      region,
      country,
      COUNT(*) FILTER (WHERE customer_segment = 'champions') as champions_count,
      COUNT(*) FILTER (WHERE customer_segment = 'loyal_customers') as loyal_customers_count,
      COUNT(*) FILTER (WHERE customer_segment = 'at_risk') as at_risk_count,
      COUNT(*) FILTER (WHERE customer_segment = 'hibernating') as hibernating_count,
      AVG(predicted_clv) as avg_predicted_clv,
      COUNT(*) FILTER (WHERE churn_risk = 'high_risk') as high_risk_customers,
      COUNT(*) FILTER (WHERE channel_preference = 'mobile_first') as mobile_first_customers,
      COUNT(*) FILTER (WHERE channel_preference = 'web_first') as web_first_customers,
      COUNT(*) FILTER (WHERE channel_preference = 'omnichannel') as omnichannel_customers
    FROM customer_segments_scored
    GROUP BY region, country
  ) css ON ga.region = css.region AND ga.country = css.country

  WHERE ga.order_year >= 2023
)

SELECT 
  region,
  country,
  order_year,
  order_quarter,

  -- Core performance metrics
  total_revenue,
  unique_customers,
  ROUND(avg_order_value::numeric, 2) as avg_order_value,

  -- Growth indicators
  COALESCE(revenue_growth_pct, 0) as revenue_growth_pct,
  COALESCE(customer_growth_pct, 0) as customer_growth_pct,
  revenue_trend,

  -- Market position
  revenue_rank,
  ROUND((revenue_percentile * 100)::numeric, 1) as revenue_percentile_rank,
  anomaly_status,

  -- Customer portfolio health
  COALESCE(champions_count, 0) as champions,
  COALESCE(loyal_customers_count, 0) as loyal_customers,
  COALESCE(at_risk_count, 0) as at_risk_customers,
  COALESCE(high_risk_customers, 0) as churn_risk_customers,

  -- Channel insights
  COALESCE(mobile_first_customers, 0) as mobile_focused,
  COALESCE(omnichannel_customers, 0) as omnichannel_users,

  -- Value predictions
  ROUND(COALESCE(avg_predicted_clv, 0)::numeric, 2) as avg_customer_ltv,

  -- Strategic guidance
  strategic_recommendation,

  -- Executive summary scoring
  CASE 
    WHEN revenue_growth_pct > 15 AND revenue_rank <= 3 THEN 'excellent'
    WHEN revenue_growth_pct > 5 AND revenue_rank <= 10 THEN 'good' 
    WHEN revenue_growth_pct >= 0 OR revenue_rank <= 20 THEN 'acceptable'
    ELSE 'needs_improvement'
  END as overall_performance_grade

FROM business_intelligence_summary
ORDER BY 
  order_year DESC,
  order_quarter DESC,
  total_revenue DESC
LIMIT 100;

-- Real-time aggregation pipeline with change streams
CREATE MATERIALIZED VIEW real_time_metrics AS
SELECT 
  DATE_TRUNC('minute', order_timestamp, 5) as time_bucket, -- 5-minute buckets
  region,

  -- Real-time KPIs
  COUNT(*) as orders_per_5min,
  SUM(total_amount) as revenue_per_5min,
  COUNT(DISTINCT user_id) as unique_customers_5min,
  AVG(total_amount) as avg_order_value_5min,

  -- Velocity metrics
  COUNT(*) / 5.0 as orders_per_minute,
  SUM(total_amount) / 5.0 as revenue_per_minute,

  -- Performance alerts
  CASE 
    WHEN COUNT(*) > 1000 THEN 'high_volume_alert'
    WHEN AVG(total_amount) < 50 THEN 'low_aov_alert'
    WHEN COUNT(DISTINCT user_id) / COUNT(*)::float < 0.7 THEN 'retention_concern'
    ELSE 'normal'
  END as alert_status,

  -- Trend indicators
  LAG(SUM(total_amount)) OVER (
    PARTITION BY region 
    ORDER BY DATE_TRUNC('minute', order_timestamp, 5)
  ) as previous_bucket_revenue,

  CURRENT_TIMESTAMP as computed_at

FROM orders
WHERE order_timestamp >= CURRENT_TIMESTAMP - INTERVAL '1 hour'
  AND status IN ('completed', 'shipped', 'delivered')
GROUP BY DATE_TRUNC('minute', order_timestamp, 5), region

-- QueryLeaf optimization features:
WITH AGGREGATION_SETTINGS (
  refresh_interval = '1 minute',
  allow_disk_use = true,
  max_memory_usage = '500M',
  parallel_processing = true,
  index_hints = ['order_timestamp_region_idx', 'user_status_idx'],
  change_stream_enabled = true
);

-- QueryLeaf provides comprehensive aggregation optimization:
-- 1. SQL-familiar syntax for complex MongoDB aggregation pipelines
-- 2. Automatic pipeline optimization with index hints and memory management
-- 3. Advanced window functions and statistical operations for analytics
-- 4. Real-time aggregation capabilities with change streams integration  
-- 5. Performance monitoring and explain plan analysis tools
-- 6. Materialized view support for frequently accessed aggregations
-- 7. Customer segmentation and RFM analysis with built-in algorithms
-- 8. Anomaly detection and alerting capabilities for operational intelligence
-- 9. Growth analysis and trend calculation functions
-- 10. Strategic business intelligence reporting with actionable insights

Best Practices for Aggregation Framework Optimization

Pipeline Design Strategy

Essential principles for building high-performance MongoDB aggregation pipelines:

  1. Early Stage Filtering: Place $match stages as early as possible to reduce documents flowing through the pipeline
  2. Index Utilization: Design indexes specifically for aggregation query patterns and filter conditions
  3. Stage Ordering: Order stages to minimize memory usage and maximize index effectiveness
  4. Memory Management: Use allowDiskUse for large dataset operations and monitor memory consumption
  5. Pipeline Composition: Break complex pipelines into reusable, testable components
  6. Performance Monitoring: Implement comprehensive explain plan analysis and execution time tracking

Production Optimization Techniques

Optimize MongoDB aggregation pipelines for production-scale workloads:

  1. Index Strategy: Create compound indexes aligned with aggregation filter and grouping patterns
  2. Memory Optimization: Balance memory usage with disk spillover for optimal performance
  3. Parallel Processing: Leverage MongoDB's parallel processing capabilities for large dataset aggregations
  4. Caching Strategies: Implement result caching and materialized views for frequently accessed aggregations
  5. Real-time Analytics: Use change streams and incremental processing for real-time analytical workloads
  6. Monitoring Integration: Deploy comprehensive performance monitoring and alerting for production pipelines

Conclusion

MongoDB's Aggregation Framework provides a powerful, flexible foundation for complex data processing and analytics that scales from simple transformations to sophisticated analytical workloads. The pipeline-based architecture enables clear, maintainable data processing workflows with extensive optimization opportunities that support both real-time and batch processing scenarios.

Key MongoDB Aggregation Framework benefits include:

  • Pipeline Clarity: Stage-based design that promotes clear, maintainable data transformation logic
  • Performance Optimization: Sophisticated optimization engine with index utilization and memory management
  • Analytical Power: Rich statistical functions and window operations for advanced analytics
  • Scalability: Horizontal scaling capabilities that support growing analytical requirements
  • Flexibility: Adaptable pipeline patterns that evolve with changing business requirements
  • Integration: Seamless integration with MongoDB's document model and distributed architecture

Whether you're building real-time dashboards, customer segmentation systems, business intelligence platforms, or complex analytical applications, MongoDB's Aggregation Framework with QueryLeaf's familiar SQL interface provides the foundation for high-performance data processing at scale.

QueryLeaf Integration: QueryLeaf automatically optimizes MongoDB aggregation pipelines while providing SQL-familiar syntax for complex analytics, window functions, and statistical operations. Advanced aggregation patterns, performance optimization, and real-time analytics capabilities are seamlessly accessible through familiar SQL constructs, making sophisticated data processing both powerful and approachable for SQL-oriented development teams.

The combination of MongoDB's flexible aggregation capabilities with SQL-style operations makes it an ideal platform for modern analytical applications that require both high performance and rapid development cycles, ensuring your data processing workflows can scale efficiently while remaining maintainable and adaptable to evolving business needs.

MongoDB Aggregation Pipeline Performance Optimization: Advanced Techniques for High-Performance Data Processing and Analytics

Modern applications increasingly rely on complex data analytics, real-time reporting, and sophisticated data transformations that demand high-performance aggregation capabilities. Poor aggregation pipeline design can lead to slow response times, excessive memory usage, and resource bottlenecks that become critical performance issues as data volumes and analytical complexity grow.

MongoDB's aggregation framework provides powerful capabilities for data processing, analysis, and transformation that can handle complex analytical workloads efficiently when properly optimized. Unlike limited relational database aggregation approaches, MongoDB pipelines support flexible document processing, nested data analysis, and sophisticated transformations that align with modern application requirements while maintaining performance at scale.

The Traditional Database Aggregation Limitations

Conventional relational database aggregation approaches impose significant constraints for modern analytical workloads:

-- Traditional PostgreSQL aggregation - rigid structure with performance limitations

-- Basic aggregation with limited optimization potential
WITH customer_metrics AS (
  SELECT 
    u.user_id,
    u.country,
    u.registration_date,
    u.status,
    COUNT(o.order_id) as order_count,
    SUM(o.total_amount) as total_spent,
    AVG(o.total_amount) as avg_order_value,
    MAX(o.created_at) as last_order_date,

    -- Limited JSON aggregation capabilities
    COUNT(CASE WHEN o.status = 'completed' THEN 1 END) as completed_orders,
    COUNT(CASE WHEN o.status = 'pending' THEN 1 END) as pending_orders,
    COUNT(CASE WHEN o.status = 'cancelled' THEN 1 END) as cancelled_orders,

    -- Basic window functions
    ROW_NUMBER() OVER (PARTITION BY u.country ORDER BY SUM(o.total_amount) DESC) as country_rank,
    PERCENT_RANK() OVER (ORDER BY SUM(o.total_amount)) as spending_percentile

  FROM users u
  LEFT JOIN orders o ON u.user_id = o.user_id
  WHERE u.registration_date >= CURRENT_DATE - INTERVAL '2 years'
    AND u.status = 'active'
  GROUP BY u.user_id, u.country, u.registration_date, u.status
),

product_analysis AS (
  SELECT 
    p.product_id,
    p.category,
    p.brand,
    p.price,
    COUNT(oi.order_item_id) as times_ordered,
    SUM(oi.quantity) as total_quantity_sold,
    SUM(oi.quantity * oi.unit_price) as total_revenue,

    -- Limited array and JSON processing
    AVG(CAST(r.rating AS NUMERIC)) as avg_rating,
    COUNT(r.review_id) as review_count,

    -- Complex subquery for related data
    (SELECT STRING_AGG(DISTINCT c.name, ', ') 
     FROM categories c 
     JOIN product_categories pc ON c.category_id = pc.category_id 
     WHERE pc.product_id = p.product_id
    ) as category_names,

    -- Percentile calculations require window functions
    PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY oi.unit_price) as price_q1,
    PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY oi.unit_price) as price_median,
    PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY oi.unit_price) as price_q3

  FROM products p
  LEFT JOIN order_items oi ON p.product_id = oi.product_id
  LEFT JOIN orders o ON oi.order_id = o.order_id
  LEFT JOIN reviews r ON p.product_id = r.product_id
  WHERE o.status = 'completed'
    AND o.created_at >= CURRENT_DATE - INTERVAL '1 year'
  GROUP BY p.product_id, p.category, p.brand, p.price
),

sales_trends AS (
  SELECT 
    DATE_TRUNC('month', o.created_at) as month,
    u.country,
    p.category,
    COUNT(o.order_id) as orders,
    SUM(o.total_amount) as revenue,
    COUNT(DISTINCT u.user_id) as unique_customers,
    AVG(o.total_amount) as avg_order_value,

    -- Complex trend calculations
    LAG(SUM(o.total_amount)) OVER (
      PARTITION BY u.country, p.category 
      ORDER BY DATE_TRUNC('month', o.created_at)
    ) as prev_month_revenue,

    -- Percentage change calculation
    CASE 
      WHEN LAG(SUM(o.total_amount)) OVER (
        PARTITION BY u.country, p.category 
        ORDER BY DATE_TRUNC('month', o.created_at)
      ) > 0 THEN
        ROUND(
          (SUM(o.total_amount) - LAG(SUM(o.total_amount)) OVER (
            PARTITION BY u.country, p.category 
            ORDER BY DATE_TRUNC('month', o.created_at)
          )) / LAG(SUM(o.total_amount)) OVER (
            PARTITION BY u.country, p.category 
            ORDER BY DATE_TRUNC('month', o.created_at)
          ) * 100, 2
        )
      ELSE NULL
    END as revenue_growth_pct

  FROM orders o
  JOIN users u ON o.user_id = u.user_id
  JOIN order_items oi ON o.order_id = oi.order_id
  JOIN products p ON oi.product_id = p.product_id
  WHERE o.status = 'completed'
    AND o.created_at >= CURRENT_DATE - INTERVAL '18 months'
  GROUP BY DATE_TRUNC('month', o.created_at), u.country, p.category
)

-- Final complex analytical query with multiple CTEs
SELECT 
  cm.country,
  COUNT(DISTINCT cm.user_id) as total_customers,
  SUM(cm.total_spent) as country_revenue,
  AVG(cm.avg_order_value) as country_avg_order_value,

  -- Customer segmentation
  COUNT(CASE WHEN cm.total_spent > 1000 THEN 1 END) as high_value_customers,
  COUNT(CASE WHEN cm.total_spent BETWEEN 100 AND 1000 THEN 1 END) as medium_value_customers,
  COUNT(CASE WHEN cm.total_spent < 100 THEN 1 END) as low_value_customers,

  -- Activity analysis
  COUNT(CASE WHEN cm.last_order_date >= CURRENT_DATE - INTERVAL '30 days' THEN 1 END) as recent_customers,
  COUNT(CASE WHEN cm.last_order_date < CURRENT_DATE - INTERVAL '90 days' THEN 1 END) as inactive_customers,

  -- Product performance correlation
  (SELECT AVG(pa.avg_rating) 
   FROM product_analysis pa 
   JOIN order_items oi ON pa.product_id = oi.product_id 
   JOIN orders o ON oi.order_id = o.order_id 
   JOIN users u ON o.user_id = u.user_id 
   WHERE u.country = cm.country) as avg_product_rating,

  -- Sales trend analysis
  (SELECT AVG(st.revenue_growth_pct) 
   FROM sales_trends st 
   WHERE st.country = cm.country 
     AND st.month >= CURRENT_DATE - INTERVAL '6 months') as avg_growth_rate,

  -- Market share calculation
  ROUND(
    SUM(cm.total_spent) / 
    (SELECT SUM(total_spent) FROM customer_metrics) * 100, 2
  ) as market_share_pct,

  -- Customer concentration (top 20% of customers by spending)
  COUNT(CASE WHEN cm.spending_percentile >= 0.8 THEN 1 END) as top_tier_customers,

  -- Ranking by country performance
  RANK() OVER (ORDER BY SUM(cm.total_spent) DESC) as country_rank,
  DENSE_RANK() OVER (ORDER BY AVG(cm.avg_order_value) DESC) as aov_rank

FROM customer_metrics cm
GROUP BY cm.country
HAVING COUNT(DISTINCT cm.user_id) >= 100  -- Filter countries with sufficient data
ORDER BY SUM(cm.total_spent) DESC, AVG(cm.avg_order_value) DESC;

-- PostgreSQL aggregation problems:
-- 1. Complex multi-table joins required for nested data analysis
-- 2. Limited support for dynamic grouping and flexible document structures
-- 3. Poor performance with large datasets requiring multiple table scans
-- 4. Inflexible aggregation stages that cannot be easily reordered or optimized
-- 5. Basic JSON aggregation capabilities with limited nested field support
-- 6. Complex window function syntax for trend analysis and rankings
-- 7. Inefficient handling of array fields and multi-value attributes
-- 8. Limited memory management options for large aggregation operations
-- 9. Rigid aggregation pipeline that cannot adapt to varying data patterns
-- 10. Poor integration with modern application data structures

-- Additional performance issues:
-- - Memory exhaustion with large GROUP BY operations
-- - Nested subquery performance degradation
-- - Complex JOIN operations across multiple large tables
-- - Limited parallel processing capabilities for aggregation stages
-- - Inefficient handling of sparse data and optional fields

-- MySQL approach (even more limited)
SELECT 
  u.country,
  COUNT(DISTINCT u.user_id) as customers,
  COUNT(o.order_id) as orders,
  SUM(o.total_amount) as revenue,
  AVG(o.total_amount) as avg_order_value,

  -- Basic JSON functions (limited capabilities)
  AVG(CAST(JSON_EXTRACT(u.profile, '$.age') AS SIGNED)) as avg_age,
  COUNT(CASE WHEN JSON_EXTRACT(u.preferences, '$.newsletter') = true THEN 1 END) as newsletter_subscribers

FROM users u
LEFT JOIN orders o ON u.user_id = o.user_id
WHERE u.status = 'active'
  AND o.created_at >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR)
GROUP BY u.country
HAVING COUNT(DISTINCT u.user_id) >= 50
ORDER BY SUM(o.total_amount) DESC;

-- MySQL limitations:
-- - Very basic JSON aggregation functions
-- - Limited window function support in older versions
-- - Poor performance with complex aggregations
-- - Basic GROUP BY optimization
-- - Limited support for nested data analysis
-- - Minimal analytical function capabilities
-- - Simple aggregation pipeline with rigid structure

MongoDB's aggregation pipeline provides comprehensive, optimized data processing:

// MongoDB Advanced Aggregation Pipeline - flexible, powerful, and performance-optimized
const { MongoClient } = require('mongodb');

const client = new MongoClient('mongodb://localhost:27017');
const db = client.db('ecommerce_analytics');

// Advanced MongoDB aggregation pipeline manager
class MongoAggregationOptimizer {
  constructor(db) {
    this.db = db;
    this.collections = {
      users: db.collection('users'),
      orders: db.collection('orders'),
      products: db.collection('products'),
      reviews: db.collection('reviews'),
      analytics: db.collection('analytics')
    };
    this.pipelineCache = new Map();
    this.performanceTargets = {
      maxExecutionTime: 5000, // 5 seconds for complex analytics
      maxMemoryUsage: 100, // 100MB memory limit
      maxStages: 20 // Maximum pipeline stages
    };
  }

  async buildComprehensiveAnalyticsPipeline() {
    console.log('Building comprehensive analytics aggregation pipeline...');

    // Advanced customer analytics with optimized pipeline
    const customerAnalyticsPipeline = [
      // Stage 1: Initial match to reduce dataset early
      {
        $match: {
          status: 'active',
          createdAt: { $gte: new Date(Date.now() - 2 * 365 * 24 * 60 * 60 * 1000) }, // Last 2 years
          totalSpent: { $exists: true }
        }
      },

      // Stage 2: Project only required fields to reduce memory usage
      {
        $project: {
          userId: '$_id',
          country: 1,
          status: 1,
          createdAt: 1,
          totalSpent: 1,
          loyaltyTier: 1,
          preferences: 1,
          // Create computed fields early in pipeline
          registrationYear: { $year: '$createdAt' },
          registrationMonth: { $month: '$createdAt' },
          customerAge: {
            $divide: [
              { $subtract: [new Date(), '$createdAt'] },
              365 * 24 * 60 * 60 * 1000 // Convert to years
            ]
          }
        }
      },

      // Stage 3: Lookup orders with targeted fields only
      {
        $lookup: {
          from: 'orders',
          localField: 'userId',
          foreignField: 'userId',
          as: 'orders',
          pipeline: [
            {
              $match: {
                status: { $in: ['completed', 'pending', 'cancelled'] },
                createdAt: { $gte: new Date(Date.now() - 365 * 24 * 60 * 60 * 1000) } // Last year
              }
            },
            {
              $project: {
                orderId: '$_id',
                status: 1,
                totalAmount: 1,
                createdAt: 1,
                items: {
                  $map: {
                    input: '$items',
                    as: 'item',
                    in: {
                      productId: '$$item.productId',
                      quantity: '$$item.quantity',
                      unitPrice: '$$item.unitPrice',
                      category: '$$item.category'
                    }
                  }
                }
              }
            }
          ]
        }
      },

      // Stage 4: Add computed fields for customer analysis
      {
        $addFields: {
          // Order statistics
          orderCount: { $size: '$orders' },
          completedOrders: {
            $size: {
              $filter: {
                input: '$orders',
                cond: { $eq: ['$$this.status', 'completed'] }
              }
            }
          },
          pendingOrders: {
            $size: {
              $filter: {
                input: '$orders',
                cond: { $eq: ['$$this.status', 'pending'] }
              }
            }
          },
          cancelledOrders: {
            $size: {
              $filter: {
                input: '$orders',
                cond: { $eq: ['$$this.status', 'cancelled'] }
              }
            }
          },

          // Revenue calculations
          totalRevenue: {
            $sum: {
              $map: {
                input: {
                  $filter: {
                    input: '$orders',
                    cond: { $eq: ['$$this.status', 'completed'] }
                  }
                },
                as: 'order',
                in: '$$order.totalAmount'
              }
            }
          },

          // Customer behavior analysis
          avgOrderValue: {
            $cond: {
              if: { $gt: [{ $size: '$orders' }, 0] },
              then: {
                $avg: {
                  $map: {
                    input: {
                      $filter: {
                        input: '$orders',
                        cond: { $eq: ['$$this.status', 'completed'] }
                      }
                    },
                    as: 'order',
                    in: '$$order.totalAmount'
                  }
                }
              },
              else: 0
            }
          },

          // Recency analysis
          lastOrderDate: {
            $max: {
              $map: {
                input: '$orders',
                as: 'order',
                in: '$$order.createdAt'
              }
            }
          },

          // Product diversity analysis
          uniqueCategories: {
            $size: {
              $setUnion: {
                $reduce: {
                  input: '$orders',
                  initialValue: [],
                  in: {
                    $setUnion: [
                      '$$value',
                      {
                        $map: {
                          input: '$$this.items',
                          as: 'item',
                          in: '$$item.category'
                        }
                      }
                    ]
                  }
                }
              }
            }
          }
        }
      },

      // Stage 5: Customer segmentation
      {
        $addFields: {
          // Value segmentation
          valueSegment: {
            $switch: {
              branches: [
                {
                  case: { $gte: ['$totalRevenue', 1000] },
                  then: 'high_value'
                },
                {
                  case: { $gte: ['$totalRevenue', 100] },
                  then: 'medium_value'
                }
              ],
              default: 'low_value'
            }
          },

          // Activity segmentation
          activitySegment: {
            $switch: {
              branches: [
                {
                  case: {
                    $gte: [
                      '$lastOrderDate',
                      new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)
                    ]
                  },
                  then: 'active'
                },
                {
                  case: {
                    $gte: [
                      '$lastOrderDate',
                      new Date(Date.now() - 90 * 24 * 60 * 60 * 1000)
                    ]
                  },
                  then: 'recent'
                },
                {
                  case: {
                    $gte: [
                      '$lastOrderDate',
                      new Date(Date.now() - 180 * 24 * 60 * 60 * 1000)
                    ]
                  },
                  then: 'inactive'
                }
              ],
              default: 'dormant'
            }
          },

          // Engagement scoring
          engagementScore: {
            $add: [
              // Order frequency component (0-40 points)
              { $multiply: [{ $min: ['$orderCount', 10] }, 4] },

              // Revenue component (0-30 points)
              { $multiply: [{ $min: [{ $divide: ['$totalRevenue', 100] }, 10] }, 3] },

              // Category diversity component (0-20 points)
              { $multiply: [{ $min: ['$uniqueCategories', 10] }, 2] },

              // Recency component (0-10 points)
              {
                $cond: {
                  if: {
                    $gte: [
                      '$lastOrderDate',
                      new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)
                    ]
                  },
                  then: 10,
                  else: {
                    $cond: {
                      if: {
                        $gte: [
                          '$lastOrderDate',
                          new Date(Date.now() - 90 * 24 * 60 * 60 * 1000)
                        ]
                      },
                      then: 5,
                      else: 0
                    }
                  }
                }
              }
            ]
          }
        }
      },

      // Stage 6: Group by country and segments for analysis
      {
        $group: {
          _id: {
            country: '$country',
            valueSegment: '$valueSegment',
            activitySegment: '$activitySegment'
          },

          // Customer counts
          customerCount: { $sum: 1 },

          // Revenue metrics
          totalRevenue: { $sum: '$totalRevenue' },
          avgRevenue: { $avg: '$totalRevenue' },
          maxRevenue: { $max: '$totalRevenue' },
          minRevenue: { $min: '$totalRevenue' },

          // Order metrics
          totalOrders: { $sum: '$orderCount' },
          avgOrdersPerCustomer: { $avg: '$orderCount' },
          totalCompletedOrders: { $sum: '$completedOrders' },

          // Behavioral metrics
          avgOrderValue: { $avg: '$avgOrderValue' },
          avgEngagementScore: { $avg: '$engagementScore' },
          avgCategoryDiversity: { $avg: '$uniqueCategories' },

          // Customer lifecycle metrics
          avgCustomerAge: { $avg: '$customerAge' },

          // Statistical measures
          revenueStdDev: { $stdDevPop: '$totalRevenue' },
          engagementStdDev: { $stdDevPop: '$engagementScore' },

          // Percentile calculations using $bucketAuto approach
          customers: {
            $push: {
              userId: '$userId',
              totalRevenue: '$totalRevenue',
              engagementScore: '$engagementScore',
              orderCount: '$orderCount'
            }
          }
        }
      },

      // Stage 7: Calculate percentiles and advanced metrics
      {
        $addFields: {
          // Revenue percentiles
          revenuePercentiles: {
            $let: {
              vars: {
                sortedRevenues: {
                  $map: {
                    input: {
                      $sortArray: {
                        input: '$customers.totalRevenue',
                        sortBy: 1
                      }
                    },
                    as: 'rev',
                    in: '$$rev'
                  }
                }
              },
              in: {
                p25: {
                  $arrayElemAt: [
                    '$$sortedRevenues',
                    { $floor: { $multiply: [{ $size: '$$sortedRevenues' }, 0.25] } }
                  ]
                },
                p50: {
                  $arrayElemAt: [
                    '$$sortedRevenues',
                    { $floor: { $multiply: [{ $size: '$$sortedRevenues' }, 0.5] } }
                  ]
                },
                p75: {
                  $arrayElemAt: [
                    '$$sortedRevenues',
                    { $floor: { $multiply: [{ $size: '$$sortedRevenues' }, 0.75] } }
                  ]
                },
                p90: {
                  $arrayElemAt: [
                    '$$sortedRevenues',
                    { $floor: { $multiply: [{ $size: '$$sortedRevenues' }, 0.9] } }
                  ]
                }
              }
            }
          },

          // Customer concentration metrics
          topCustomerRevenue: {
            $sum: {
              $slice: [
                {
                  $sortArray: {
                    input: '$customers.totalRevenue',
                    sortBy: -1
                  }
                },
                { $min: [{ $ceil: { $multiply: ['$customerCount', 0.2] } }, 10] }
              ]
            }
          }
        }
      },

      // Stage 8: Add market analysis
      {
        $addFields: {
          // Customer concentration (top 20% revenue share)
          customerConcentration: {
            $divide: ['$topCustomerRevenue', '$totalRevenue']
          },

          // Segment performance indicators
          performanceIndicators: {
            revenuePerCustomer: { $divide: ['$totalRevenue', '$customerCount'] },
            ordersPerCustomer: { $divide: ['$totalOrders', '$customerCount'] },
            completionRate: {
              $cond: {
                if: { $gt: ['$totalOrders', 0] },
                then: { $divide: ['$totalCompletedOrders', '$totalOrders'] },
                else: 0
              }
            }
          },

          // Growth potential scoring
          growthPotential: {
            $switch: {
              branches: [
                {
                  case: {
                    $and: [
                      { $eq: ['$_id.valueSegment', 'high_value'] },
                      { $eq: ['$_id.activitySegment', 'active'] }
                    ]
                  },
                  then: 'maintain'
                },
                {
                  case: {
                    $and: [
                      { $eq: ['$_id.valueSegment', 'high_value'] },
                      { $ne: ['$_id.activitySegment', 'active'] }
                    ]
                  },
                  then: 'reactivate'
                },
                {
                  case: {
                    $and: [
                      { $ne: ['$_id.valueSegment', 'low_value'] },
                      { $eq: ['$_id.activitySegment', 'active'] }
                    ]
                  },
                  then: 'upsell'
                },
                {
                  case: { $eq: ['$_id.activitySegment', 'dormant'] },
                  then: 'winback'
                }
              ],
              default: 'nurture'
            }
          }
        }
      },

      // Stage 9: Remove detailed customer data to reduce output size
      {
        $project: {
          customers: 0 // Remove large array to optimize output
        }
      },

      // Stage 10: Sort by strategic importance
      {
        $sort: {
          totalRevenue: -1,
          customerCount: -1,
          '_id.country': 1
        }
      },

      // Stage 11: Add final computed fields for presentation
      {
        $addFields: {
          segmentId: {
            $concat: [
              '$_id.country',
              '_',
              '$_id.valueSegment',
              '_',
              '$_id.activitySegment'
            ]
          },

          // Strategic priority scoring
          strategicPriority: {
            $add: [
              // Revenue weight (40%)
              { $multiply: [{ $divide: ['$totalRevenue', 10000] }, 0.4] },

              // Customer count weight (30%)
              { $multiply: [{ $divide: ['$customerCount', 100] }, 0.3] },

              // Engagement weight (20%)
              { $multiply: [{ $divide: ['$avgEngagementScore', 100] }, 0.2] },

              // Growth potential weight (10%)
              {
                $switch: {
                  branches: [
                    { case: { $eq: ['$growthPotential', 'upsell'] }, then: 0.1 },
                    { case: { $eq: ['$growthPotential', 'reactivate'] }, then: 0.08 },
                    { case: { $eq: ['$growthPotential', 'maintain'] }, then: 0.06 },
                    { case: { $eq: ['$growthPotential', 'nurture'] }, then: 0.04 }
                  ],
                  default: 0.02
                }
              }
            ]
          }
        }
      }
    ];

    console.log('Executing comprehensive customer analytics pipeline...');
    const startTime = Date.now();

    try {
      const results = await this.collections.users.aggregate(
        customerAnalyticsPipeline,
        {
          allowDiskUse: true, // Enable disk usage for large datasets
          maxTimeMS: this.performanceTargets.maxExecutionTime,
          hint: { status: 1, createdAt: 1, totalSpent: 1 }, // Suggest optimal index
          cursor: { batchSize: 1000 } // Optimize cursor batch size
        }
      ).toArray();

      const executionTime = Date.now() - startTime;

      console.log(`Pipeline executed successfully in ${executionTime}ms`);
      console.log(`Processed ${results.length} customer segments`);

      // Cache results for performance optimization
      this.pipelineCache.set('customer_analytics', {
        results,
        timestamp: new Date(),
        executionTime
      });

      return {
        results,
        executionStats: {
          executionTime,
          segmentsAnalyzed: results.length,
          performanceGrade: this.calculatePerformanceGrade(executionTime)
        }
      };

    } catch (error) {
      console.error('Pipeline execution failed:', error);
      throw error;
    }
  }

  async buildProductPerformanceAnalytics() {
    console.log('Building product performance analytics pipeline...');

    const productAnalyticsPipeline = [
      // Stage 1: Match active products with recent sales
      {
        $match: {
          status: 'active',
          createdAt: { $gte: new Date(Date.now() - 365 * 24 * 60 * 60 * 1000) }
        }
      },

      // Stage 2: Lookup orders and reviews with sub-pipeline optimization
      {
        $lookup: {
          from: 'orders',
          let: { productId: '$_id' },
          pipeline: [
            {
              $match: {
                $expr: {
                  $and: [
                    { $in: ['$$productId', '$items.productId'] },
                    { $eq: ['$status', 'completed'] },
                    { $gte: ['$createdAt', new Date(Date.now() - 365 * 24 * 60 * 60 * 1000)] }
                  ]
                }
              }
            },
            {
              $unwind: '$items'
            },
            {
              $match: {
                $expr: { $eq: ['$items.productId', '$$productId'] }
              }
            },
            {
              $project: {
                orderId: '$_id',
                userId: 1,
                createdAt: 1,
                quantity: '$items.quantity',
                unitPrice: '$items.unitPrice',
                revenue: { $multiply: ['$items.quantity', '$items.unitPrice'] }
              }
            }
          ],
          as: 'sales'
        }
      },

      // Stage 3: Lookup reviews with aggregation
      {
        $lookup: {
          from: 'reviews',
          localField: '_id',
          foreignField: 'productId',
          pipeline: [
            {
              $match: {
                status: 'published',
                rating: { $gte: 1, $lte: 5 }
              }
            },
            {
              $group: {
                _id: null,
                avgRating: { $avg: '$rating' },
                reviewCount: { $sum: 1 },
                ratingDistribution: {
                  $push: {
                    rating: '$rating',
                    helpful: '$helpfulVotes',
                    sentiment: '$sentiment'
                  }
                }
              }
            }
          ],
          as: 'reviewMetrics'
        }
      },

      // Stage 4: Calculate comprehensive product metrics
      {
        $addFields: {
          // Sales performance
          totalSales: { $size: '$sales' },
          totalRevenue: { $sum: '$sales.revenue' },
          totalQuantitySold: { $sum: '$sales.quantity' },
          avgOrderQuantity: { $avg: '$sales.quantity' },
          avgUnitPrice: { $avg: '$sales.unitPrice' },

          // Customer metrics
          uniqueCustomers: {
            $size: {
              $setUnion: {
                $map: {
                  input: '$sales',
                  as: 'sale',
                  in: '$$sale.userId'
                }
              }
            }
          },

          // Temporal analysis
          salesByMonth: {
            $reduce: {
              input: {
                $map: {
                  input: '$sales',
                  as: 'sale',
                  in: {
                    month: { $dateToString: { format: '%Y-%m', date: '$$sale.createdAt' } },
                    revenue: '$$sale.revenue',
                    quantity: '$$sale.quantity'
                  }
                }
              },
              initialValue: {},
              in: {
                $mergeObjects: [
                  '$$value',
                  {
                    $arrayToObject: [
                      [{
                        k: '$$this.month',
                        v: {
                          revenue: { $add: [{ $ifNull: [{ $getField: { field: '$$this.month', input: '$$value' } }.revenue, 0] }, '$$this.revenue'] },
                          quantity: { $add: [{ $ifNull: [{ $getField: { field: '$$this.month', input: '$$value' } }.quantity, 0] }, '$$this.quantity'] },
                          orders: { $add: [{ $ifNull: [{ $getField: { field: '$$this.month', input: '$$value' } }.orders, 0] }, 1] }
                        }
                      }]
                    ]
                  }
                ]
              }
            }
          },

          // Review metrics
          avgRating: { $arrayElemAt: ['$reviewMetrics.avgRating', 0] },
          reviewCount: { $arrayElemAt: ['$reviewMetrics.reviewCount', 0] },

          // Performance indicators
          salesVelocity: {
            $cond: {
              if: { $gt: [{ $size: '$sales' }, 0] },
              then: {
                $divide: [
                  { $size: '$sales' },
                  {
                    $divide: [
                      {
                        $subtract: [
                          new Date(),
                          { $min: '$sales.createdAt' }
                        ]
                      },
                      30 * 24 * 60 * 60 * 1000 // 30-day periods
                    ]
                  }
                ]
              },
              else: 0
            }
          }
        }
      },

      // Stage 5: Product classification and scoring
      {
        $addFields: {
          // Performance classification
          performanceClass: {
            $switch: {
              branches: [
                {
                  case: {
                    $and: [
                      { $gte: ['$totalRevenue', 10000] },
                      { $gte: ['$uniqueCustomers', 100] },
                      { $gte: [{ $ifNull: ['$avgRating', 0] }, 4.0] }
                    ]
                  },
                  then: 'star'
                },
                {
                  case: {
                    $and: [
                      { $gte: ['$totalRevenue', 5000] },
                      { $gte: ['$uniqueCustomers', 50] },
                      { $gte: [{ $ifNull: ['$avgRating', 0] }, 3.5] }
                    ]
                  },
                  then: 'strong'
                },
                {
                  case: {
                    $and: [
                      { $gte: ['$totalRevenue', 1000] },
                      { $gte: ['$uniqueCustomers', 20] }
                    ]
                  },
                  then: 'growing'
                },
                {
                  case: { $lte: ['$totalSales', 5] },
                  then: 'new'
                }
              ],
              default: 'underperforming'
            }
          },

          // Profitability scoring (simplified model)
          profitabilityScore: {
            $multiply: [
              // Revenue factor (40%)
              { $multiply: [{ $divide: ['$totalRevenue', 1000] }, 0.4] },

              // Customer satisfaction factor (30%)
              { $multiply: [{ $divide: [{ $ifNull: ['$avgRating', 3] }, 5] }, 0.3] },

              // Market penetration factor (20%)
              { $multiply: [{ $divide: ['$uniqueCustomers', 100] }, 0.2] },

              // Sales velocity factor (10%)
              { $multiply: [{ $min: ['$salesVelocity', 10] }, 0.01] }
            ]
          },

          // Inventory turnover estimation
          inventoryTurnover: {
            $cond: {
              if: { $and: [{ $gt: ['$stock', 0] }, { $gt: ['$totalQuantitySold', 0] }] },
              then: { $divide: ['$totalQuantitySold', '$stock'] },
              else: 0
            }
          }
        }
      },

      // Stage 6: Group by category for market analysis
      {
        $group: {
          _id: {
            category: '$category',
            brand: '$brand',
            performanceClass: '$performanceClass'
          },

          productCount: { $sum: 1 },

          // Revenue aggregations
          totalCategoryRevenue: { $sum: '$totalRevenue' },
          avgProductRevenue: { $avg: '$totalRevenue' },
          maxProductRevenue: { $max: '$totalRevenue' },

          // Customer aggregations
          totalUniqueCustomers: { $sum: '$uniqueCustomers' },
          avgCustomersPerProduct: { $avg: '$uniqueCustomers' },

          // Rating aggregations
          avgCategoryRating: { $avg: { $ifNull: ['$avgRating', 0] } },
          avgReviewCount: { $avg: { $ifNull: ['$reviewCount', 0] } },

          // Performance aggregations
          avgProfitabilityScore: { $avg: '$profitabilityScore' },
          avgSalesVelocity: { $avg: '$salesVelocity' },
          avgInventoryTurnover: { $avg: '$inventoryTurnover' },

          // Product examples for reference
          topProducts: {
            $push: {
              $cond: {
                if: { $gte: ['$profitabilityScore', 5] },
                then: {
                  productId: '$_id',
                  name: '$name',
                  revenue: '$totalRevenue',
                  rating: '$avgRating',
                  profitabilityScore: '$profitabilityScore'
                },
                else: '$$REMOVE'
              }
            }
          }
        }
      },

      // Stage 7: Calculate category market share
      {
        $addFields: {
          topProducts: { $slice: [{ $sortArray: { input: '$topProducts', sortBy: { profitabilityScore: -1 } } }, 3] }
        }
      },

      // Stage 8: Add competitive analysis
      {
        $lookup: {
          from: 'products',
          let: { currentCategory: '$_id.category' },
          pipeline: [
            {
              $match: {
                $expr: { $eq: ['$category', '$$currentCategory'] },
                status: 'active'
              }
            },
            {
              $group: {
                _id: null,
                totalCategoryProducts: { $sum: 1 },
                avgCategoryPrice: { $avg: '$price' },
                categoryPriceRange: {
                  min: { $min: '$price' },
                  max: { $max: '$price' }
                }
              }
            }
          ],
          as: 'categoryContext'
        }
      },

      // Stage 9: Final metrics and insights
      {
        $addFields: {
          // Market share within category
          categoryMarketShare: {
            $divide: [
              '$productCount',
              { $arrayElemAt: ['$categoryContext.totalCategoryProducts', 0] }
            ]
          },

          // Performance vs category average
          performanceVsCategory: {
            $divide: [
              '$avgProductRevenue',
              { $arrayElemAt: ['$categoryContext.avgCategoryPrice', 0] }
            ]
          },

          // Strategic recommendations
          strategicRecommendation: {
            $switch: {
              branches: [
                {
                  case: {
                    $and: [
                      { $eq: ['$_id.performanceClass', 'star'] },
                      { $gte: ['$avgInventoryTurnover', 4] }
                    ]
                  },
                  then: 'expand_and_invest'
                },
                {
                  case: {
                    $and: [
                      { $eq: ['$_id.performanceClass', 'strong'] },
                      { $gte: ['$categoryMarketShare', 0.1] }
                    ]
                  },
                  then: 'market_leader_strategy'
                },
                {
                  case: { $eq: ['$_id.performanceClass', 'growing'] },
                  then: 'nurture_and_optimize'
                },
                {
                  case: { $eq: ['$_id.performanceClass', 'underperforming'] },
                  then: 'review_and_improve'
                }
              ],
              default: 'monitor'
            }
          }
        }
      },

      // Stage 10: Clean up and sort
      {
        $project: {
          categoryContext: 0 // Remove lookup data to reduce output size
        }
      },

      {
        $sort: {
          totalCategoryRevenue: -1,
          avgProfitabilityScore: -1,
          '_id.category': 1
        }
      }
    ];

    console.log('Executing product performance analytics pipeline...');
    const startTime = Date.now();

    try {
      const results = await this.collections.products.aggregate(
        productAnalyticsPipeline,
        {
          allowDiskUse: true,
          maxTimeMS: this.performanceTargets.maxExecutionTime,
          cursor: { batchSize: 500 }
        }
      ).toArray();

      const executionTime = Date.now() - startTime;

      console.log(`Product analytics pipeline executed in ${executionTime}ms`);
      console.log(`Analyzed ${results.length} product categories`);

      return {
        results,
        executionStats: {
          executionTime,
          categoriesAnalyzed: results.length,
          performanceGrade: this.calculatePerformanceGrade(executionTime)
        }
      };

    } catch (error) {
      console.error('Product analytics pipeline failed:', error);
      throw error;
    }
  }

  async buildTimeSeriesAnalytics() {
    console.log('Building time-series analytics pipeline...');

    const timeSeriesPipeline = [
      // Stage 1: Match recent orders for trend analysis
      {
        $match: {
          status: 'completed',
          createdAt: {
            $gte: new Date(Date.now() - 18 * 30 * 24 * 60 * 60 * 1000) // 18 months
          }
        }
      },

      // Stage 2: Create time buckets and extract relevant fields
      {
        $addFields: {
          // Multiple time granularities
          yearMonth: { $dateToString: { format: '%Y-%m', date: '$createdAt' } },
          year: { $year: '$createdAt' },
          month: { $month: '$createdAt' },
          quarter: { $ceil: { $divide: [{ $month: '$createdAt' }, 3] } },
          weekOfYear: { $week: '$createdAt' },
          dayOfWeek: { $dayOfWeek: '$createdAt' },
          hourOfDay: { $hour: '$createdAt' },

          // Business metrics
          itemCount: { $size: '$items' },
          avgItemPrice: { $avg: '$items.unitPrice' }
        }
      },

      // Stage 3: Unwind items for product-level analysis
      {
        $unwind: '$items'
      },

      // Stage 4: Group by time periods with comprehensive metrics
      {
        $group: {
          _id: {
            yearMonth: '$yearMonth',
            year: '$year',
            month: '$month',
            quarter: '$quarter',
            category: '$items.category',
            userCountry: '$userCountry'
          },

          // Volume metrics
          orderCount: { $sum: 1 },
          totalRevenue: { $sum: { $multiply: ['$items.quantity', '$items.unitPrice'] } },
          totalQuantity: { $sum: '$items.quantity' },
          uniqueCustomers: { $addToSet: '$userId' },
          uniqueProducts: { $addToSet: '$items.productId' },

          // Average metrics
          avgOrderValue: { $avg: '$totalAmount' },
          avgQuantityPerOrder: { $avg: '$items.quantity' },
          avgUnitPrice: { $avg: '$items.unitPrice' },

          // Distribution metrics
          orderSizes: { $push: '$totalAmount' },
          customerFrequency: { $push: '$userId' },

          // Time-based patterns
          hourDistribution: {
            $push: {
              hour: '$hourOfDay',
              dayOfWeek: '$dayOfWeek',
              amount: '$totalAmount'
            }
          },

          // Product performance
          productMix: {
            $push: {
              productId: '$items.productId',
              category: '$items.category',
              quantity: '$items.quantity',
              revenue: { $multiply: ['$items.quantity', '$items.unitPrice'] }
            }
          }
        }
      },

      // Stage 5: Calculate advanced time-series metrics
      {
        $addFields: {
          uniqueCustomerCount: { $size: '$uniqueCustomers' },
          uniqueProductCount: { $size: '$uniqueProducts' },

          // Customer behavior metrics
          repeatCustomerRate: {
            $divide: [
              {
                $size: {
                  $filter: {
                    input: {
                      $reduce: {
                        input: '$customerFrequency',
                        initialValue: {},
                        in: {
                          $mergeObjects: [
                            '$$value',
                            {
                              $arrayToObject: [
                                [{
                                  k: { $toString: '$$this' },
                                  v: { $add: [{ $ifNull: [{ $getField: { field: { $toString: '$$this' }, input: '$$value' } }, 0] }, 1] }
                                }]
                              ]
                            }
                          ]
                        }
                      }
                    },
                    cond: { $gt: ['$$this.v', 1] }
                  }
                }
              },
              '$uniqueCustomerCount'
            ]
          },

          // Revenue concentration (top 20% of orders)
          revenueConcentration: {
            $let: {
              vars: {
                sortedOrders: { $sortArray: { input: '$orderSizes', sortBy: -1 } },
                top20PercentCount: { $ceil: { $multiply: ['$orderCount', 0.2] } }
              },
              in: {
                $divide: [
                  { $sum: { $slice: ['$$sortedOrders', '$$top20PercentCount'] } },
                  '$totalRevenue'
                ]
              }
            }
          },

          // Peak hour analysis
          peakHours: {
            $let: {
              vars: {
                hourlyTotals: {
                  $reduce: {
                    input: '$hourDistribution',
                    initialValue: {},
                    in: {
                      $mergeObjects: [
                        '$$value',
                        {
                          $arrayToObject: [
                            [{
                              k: { $toString: '$$this.hour' },
                              v: {
                                orders: { $add: [{ $ifNull: [{ $getField: { field: { $toString: '$$this.hour' }, input: '$$value' } }.orders, 0] }, 1] },
                                revenue: { $add: [{ $ifNull: [{ $getField: { field: { $toString: '$$this.hour' }, input: '$$value' } }.revenue, 0] }, '$$this.amount'] }
                              }
                            }]
                          ]
                        }
                      ]
                    }
                  }
                }
              },
              in: {
                $arrayElemAt: [
                  {
                    $sortArray: {
                      input: {
                        $objectToArray: '$$hourlyTotals'
                      },
                      sortBy: { 'v.revenue': -1 }
                    }
                  },
                  0
                ]
              }
            }
          }
        }
      },

      // Stage 6: Sort for time-series analysis
      {
        $sort: {
          '_id.year': 1,
          '_id.month': 1,
          '_id.category': 1,
          '_id.userCountry': 1
        }
      },

      // Stage 7: Window functions for trend analysis
      {
        $setWindowFields: {
          partitionBy: { category: '$_id.category', country: '$_id.userCountry' },
          sortBy: { '_id.year': 1, '_id.month': 1 },
          output: {
            // Moving averages
            movingAvgRevenue: {
              $avg: '$totalRevenue',
              window: { range: [-2, 0], unit: 'position' } // 3-month moving average
            },

            movingAvgOrders: {
              $avg: '$orderCount',
              window: { range: [-2, 0], unit: 'position' }
            },

            // Growth calculations
            prevMonthRevenue: {
              $shift: { output: '$totalRevenue', by: -1 }
            },

            prevYearRevenue: {
              $shift: { output: '$totalRevenue', by: -12 }
            },

            // Ranking
            revenueRank: {
              $denseRank: {}
            },

            // Cumulative metrics
            cumulativeRevenue: {
              $sum: '$totalRevenue',
              window: { range: ['unbounded', 0], unit: 'position' }
            }
          }
        }
      },

      // Stage 8: Calculate growth rates and trends
      {
        $addFields: {
          // Month-over-month growth
          momGrowthRate: {
            $cond: {
              if: { $and: [{ $ne: ['$prevMonthRevenue', null] }, { $gt: ['$prevMonthRevenue', 0] }] },
              then: {
                $multiply: [
                  {
                    $divide: [
                      { $subtract: ['$totalRevenue', '$prevMonthRevenue'] },
                      '$prevMonthRevenue'
                    ]
                  },
                  100
                ]
              },
              else: null
            }
          },

          // Year-over-year growth
          yoyGrowthRate: {
            $cond: {
              if: { $and: [{ $ne: ['$prevYearRevenue', null] }, { $gt: ['$prevYearRevenue', 0] }] },
              then: {
                $multiply: [
                  {
                    $divide: [
                      { $subtract: ['$totalRevenue', '$prevYearRevenue'] },
                      '$prevYearRevenue'
                    ]
                  },
                  100
                ]
              },
              else: null
            }
          },

          // Trend classification
          trendClassification: {
            $switch: {
              branches: [
                {
                  case: {
                    $and: [
                      { $gte: [{ $ifNull: ['$momGrowthRate', 0] }, 10] },
                      { $gte: ['$totalRevenue', '$movingAvgRevenue'] }
                    ]
                  },
                  then: 'strong_growth'
                },
                {
                  case: {
                    $and: [
                      { $gte: [{ $ifNull: ['$momGrowthRate', 0] }, 0] },
                      { $lte: [{ $ifNull: ['$momGrowthRate', 0] }, 10] }
                    ]
                  },
                  then: 'steady_growth'
                },
                {
                  case: { $lt: [{ $ifNull: ['$momGrowthRate', 0] }, -10] },
                  then: 'declining'
                }
              ],
              default: 'stable'
            }
          },

          // Seasonality indicators
          seasonalityScore: {
            $cond: {
              if: { $in: ['$_id.month', [11, 12, 1]] }, // Holiday season
              then: 1.2,
              else: {
                $cond: {
                  if: { $in: ['$_id.month', [6, 7, 8]] }, // Summer
                  then: 0.9,
                  else: 1.0
                }
              }
            }
          }
        }
      },

      // Stage 9: Final grouping for summary insights
      {
        $group: {
          _id: {
            category: '$_id.category',
            country: '$_id.userCountry'
          },

          // Time series data points
          monthlyData: {
            $push: {
              yearMonth: '$_id.yearMonth',
              revenue: '$totalRevenue',
              orders: '$orderCount',
              customers: '$uniqueCustomerCount',
              avgOrderValue: '$avgOrderValue',
              momGrowth: '$momGrowthRate',
              yoyGrowth: '$yoyGrowthRate',
              trend: '$trendClassification'
            }
          },

          // Summary statistics
          totalPeriodRevenue: { $sum: '$totalRevenue' },
          totalPeriodOrders: { $sum: '$orderCount' },
          avgMonthlyRevenue: { $avg: '$totalRevenue' },

          // Growth metrics
          avgMomGrowth: { $avg: { $ifNull: ['$momGrowthRate', 0] } },
          avgYoyGrowth: { $avg: { $ifNull: ['$yoyGrowthRate', 0] } },

          // Volatility measures
          revenueVolatility: { $stdDevPop: '$totalRevenue' },
          orderVolatility: { $stdDevPop: '$orderCount' },

          // Trend analysis
          trendDistribution: {
            $push: '$trendClassification'
          },

          // Peak performance
          peakMonthRevenue: { $max: '$totalRevenue' },
          peakMonthOrders: { $max: '$orderCount' }
        }
      },

      // Stage 10: Final insights and recommendations
      {
        $addFields: {
          // Dominant trend
          dominantTrend: {
            $let: {
              vars: {
                trendCounts: {
                  $reduce: {
                    input: '$trendDistribution',
                    initialValue: {},
                    in: {
                      $mergeObjects: [
                        '$$value',
                        {
                          $arrayToObject: [
                            [{
                              k: '$$this',
                              v: { $add: [{ $ifNull: [{ $getField: { field: '$$this', input: '$$value' } }, 0] }, 1] }
                            }]
                          ]
                        }
                      ]
                    }
                  }
                }
              },
              in: {
                $arrayElemAt: [
                  {
                    $sortArray: {
                      input: { $objectToArray: '$$trendCounts' },
                      sortBy: { v: -1 }
                    }
                  },
                  0
                ]
              }
            }
          },

          // Performance classification
          performanceClassification: {
            $switch: {
              branches: [
                {
                  case: {
                    $and: [
                      { $gte: ['$avgYoyGrowth', 20] },
                      { $lte: ['$revenueVolatility', '$avgMonthlyRevenue'] }
                    ]
                  },
                  then: 'high_growth_stable'
                },
                {
                  case: { $gte: ['$avgYoyGrowth', 20] },
                  then: 'high_growth_volatile'
                },
                {
                  case: {
                    $and: [
                      { $gte: ['$avgYoyGrowth', 5] },
                      { $lte: ['$revenueVolatility', '$avgMonthlyRevenue'] }
                    ]
                  },
                  then: 'steady_growth'
                },
                {
                  case: { $lt: ['$avgYoyGrowth', -5] },
                  then: 'declining'
                }
              ],
              default: 'mature_stable'
            }
          }
        }
      },

      {
        $sort: {
          totalPeriodRevenue: -1,
          avgYoyGrowth: -1
        }
      }
    ];

    console.log('Executing time-series analytics pipeline...');
    const startTime = Date.now();

    try {
      const results = await this.collections.orders.aggregate(
        timeSeriesPipeline,
        {
          allowDiskUse: true,
          maxTimeMS: this.performanceTargets.maxExecutionTime,
          cursor: { batchSize: 100 }
        }
      ).toArray();

      const executionTime = Date.now() - startTime;

      console.log(`Time-series analytics executed in ${executionTime}ms`);
      console.log(`Analyzed ${results.length} category-country combinations`);

      return {
        results,
        executionStats: {
          executionTime,
          timeSeriesAnalyzed: results.length,
          performanceGrade: this.calculatePerformanceGrade(executionTime)
        }
      };

    } catch (error) {
      console.error('Time-series analytics failed:', error);
      throw error;
    }
  }

  calculatePerformanceGrade(executionTimeMs) {
    // Performance grading based on execution time
    if (executionTimeMs <= 1000) return 'A';
    if (executionTimeMs <= 2500) return 'B';
    if (executionTimeMs <= 5000) return 'C';
    if (executionTimeMs <= 10000) return 'D';
    return 'F';
  }

  async optimizePipelinePerformance(pipeline, options = {}) {
    console.log('Optimizing aggregation pipeline performance...');

    const {
      enableIndexHints = true,
      enableDiskUsage = true,
      optimizeBatchSize = true,
      enablePipelineReordering = true
    } = options;

    // Performance optimization strategies
    const optimizedPipeline = [...pipeline];

    if (enablePipelineReordering) {
      // Move $match stages to the beginning
      const matchStages = [];
      const otherStages = [];

      for (const stage of optimizedPipeline) {
        if (stage.$match) {
          matchStages.push(stage);
        } else {
          otherStages.push(stage);
        }
      }

      // Reorder: matches first, then other stages
      optimizedPipeline.length = 0;
      optimizedPipeline.push(...matchStages, ...otherStages);
    }

    // Add $project stages early to reduce data size
    const hasEarlyProject = optimizedPipeline.slice(0, 3).some(stage => stage.$project);
    if (!hasEarlyProject && optimizedPipeline.length > 5) {
      // Insert projection after initial match stages
      const insertIndex = optimizedPipeline.findIndex(stage => !stage.$match) || 1;
      optimizedPipeline.splice(insertIndex, 0, {
        $project: {
          // Project only commonly used fields
          _id: 1,
          status: 1,
          createdAt: 1,
          totalAmount: 1,
          userId: 1,
          items: 1
        }
      });
    }

    // Aggregation options
    const aggregationOptions = {
      allowDiskUse: enableDiskUsage,
      maxTimeMS: this.performanceTargets.maxExecutionTime
    };

    if (optimizeBatchSize) {
      aggregationOptions.cursor = { batchSize: 1000 };
    }

    if (enableIndexHints) {
      // Suggest optimal index based on initial match conditions
      const firstMatch = optimizedPipeline.find(stage => stage.$match);
      if (firstMatch) {
        const matchFields = Object.keys(firstMatch.$match);
        aggregationOptions.hint = this.suggestOptimalIndex(matchFields);
      }
    }

    return {
      optimizedPipeline,
      aggregationOptions,
      optimizations: {
        reorderedStages: enablePipelineReordering,
        addedEarlyProjection: !hasEarlyProject && optimizedPipeline.length > 5,
        indexHint: aggregationOptions.hint || null,
        diskUsageEnabled: enableDiskUsage
      }
    };
  }

  suggestOptimalIndex(matchFields) {
    // Simple heuristic for index suggestion
    const indexSuggestions = {
      status: { status: 1 },
      createdAt: { createdAt: -1 },
      userId: { userId: 1 },
      totalAmount: { totalAmount: -1 }
    };

    // Return compound index if multiple fields
    if (matchFields.length > 1) {
      const compoundIndex = {};
      for (const field of matchFields) {
        if (field === 'createdAt' || field === 'totalAmount') {
          compoundIndex[field] = -1;
        } else {
          compoundIndex[field] = 1;
        }
      }
      return compoundIndex;
    }

    return indexSuggestions[matchFields[0]] || { [matchFields[0]]: 1 };
  }

  async analyzePipelinePerformance(collection, pipeline) {
    console.log('Analyzing pipeline performance...');

    try {
      // Execute explain to get execution statistics
      const explainResult = await collection.aggregate(pipeline).explain('executionStats');

      const analysis = {
        totalExecutionTime: this.extractExecutionTime(explainResult),
        stageBreakdown: this.analyzeStagePerformance(explainResult),
        indexUsage: this.analyzeIndexUsage(explainResult),
        memoryUsage: this.estimateMemoryUsage(explainResult),
        recommendations: []
      };

      // Generate optimization recommendations
      analysis.recommendations = this.generatePipelineRecommendations(analysis);

      return analysis;

    } catch (error) {
      console.error('Pipeline analysis failed:', error);
      return {
        error: error.message,
        recommendations: ['Unable to analyze pipeline - check syntax and data availability']
      };
    }
  }

  extractExecutionTime(explainResult) {
    // Extract execution time from explain result
    if (explainResult.stages && explainResult.stages.length > 0) {
      const lastStage = explainResult.stages[explainResult.stages.length - 1];
      return lastStage.$cursor?.executionStats?.executionTimeMillis || 0;
    }
    return 0;
  }

  analyzeStagePerformance(explainResult) {
    // Analyze performance of individual pipeline stages
    if (!explainResult.stages) return [];

    return explainResult.stages.map((stage, index) => {
      const stageInfo = {
        stageIndex: index,
        stageType: Object.keys(stage)[0],
        executionTime: 0,
        documentsProcessed: 0,
        documentsOutput: 0
      };

      // Extract stage-specific metrics
      if (stage.$cursor?.executionStats) {
        stageInfo.executionTime = stage.$cursor.executionStats.executionTimeMillis;
        stageInfo.documentsProcessed = stage.$cursor.executionStats.totalDocsExamined;
        stageInfo.documentsOutput = stage.$cursor.executionStats.totalDocsReturned;
      }

      return stageInfo;
    });
  }

  analyzeIndexUsage(explainResult) {
    // Analyze index usage patterns
    const indexUsage = {
      indexesUsed: [],
      collectionScans: 0,
      indexScans: 0,
      efficiency: 0
    };

    // Implementation would analyze explain result for index usage
    // This is a simplified version

    return indexUsage;
  }

  estimateMemoryUsage(explainResult) {
    // Estimate memory usage based on pipeline operations
    let estimatedMemory = 0;

    if (explainResult.stages) {
      for (const stage of explainResult.stages) {
        // Estimate memory for different stage types
        const stageType = Object.keys(stage)[0];

        switch (stageType) {
          case '$group':
            estimatedMemory += 10; // MB estimate
            break;
          case '$sort':
            estimatedMemory += 20; // MB estimate
            break;
          case '$lookup':
            estimatedMemory += 15; // MB estimate
            break;
          default:
            estimatedMemory += 2; // MB estimate
        }
      }
    }

    return estimatedMemory;
  }

  generatePipelineRecommendations(analysis) {
    const recommendations = [];

    // High execution time
    if (analysis.totalExecutionTime > this.performanceTargets.maxExecutionTime) {
      recommendations.push({
        type: 'PERFORMANCE_WARNING',
        message: `Pipeline execution time (${analysis.totalExecutionTime}ms) exceeds target`,
        suggestion: 'Consider adding indexes, reducing data volume, or optimizing pipeline stages'
      });
    }

    // High memory usage
    if (analysis.memoryUsage > this.performanceTargets.maxMemoryUsage) {
      recommendations.push({
        type: 'MEMORY_WARNING',
        message: `Estimated memory usage (${analysis.memoryUsage}MB) may cause performance issues`,
        suggestion: 'Enable allowDiskUse option or reduce pipeline complexity'
      });
    }

    // Collection scans detected
    if (analysis.indexUsage.collectionScans > 0) {
      recommendations.push({
        type: 'INDEX_MISSING',
        message: 'Pipeline includes collection scans',
        suggestion: 'Create indexes for fields used in $match stages'
      });
    }

    return recommendations;
  }
}

// Benefits of MongoDB Advanced Aggregation Pipelines:
// - Flexible multi-stage data processing with optimizable pipeline ordering
// - Rich aggregation operators supporting complex calculations and transformations
// - Built-in memory management with disk usage options for large datasets
// - Advanced analytical capabilities including window functions and time-series analysis
// - Efficient handling of nested documents and array operations
// - Comprehensive performance monitoring and optimization recommendations
// - Integration with MongoDB's query optimizer and index system
// - Support for real-time analytics and complex business intelligence queries
// - Scalable architecture that works across replica sets and sharded clusters
// - SQL-familiar aggregation patterns through QueryLeaf integration

module.exports = {
  MongoAggregationOptimizer
};

Understanding MongoDB Aggregation Architecture

Advanced Pipeline Design Patterns and Optimization Strategies

Implement sophisticated aggregation patterns for optimal performance and analytical capabilities:

// Advanced aggregation patterns for specialized analytical use cases
class AdvancedAggregationPatterns {
  constructor(db) {
    this.db = db;
    this.performanceMetrics = new Map();
    this.pipelineTemplates = new Map();
  }

  async implementRealTimeAnalytics() {
    console.log('Implementing real-time analytics aggregation patterns...');

    // Real-time dashboard metrics with incremental processing
    const realTimeDashboardPipeline = [
      // Stage 1: Match recent data only (last 24 hours)
      {
        $match: {
          createdAt: { $gte: new Date(Date.now() - 24 * 60 * 60 * 1000) },
          status: { $in: ['completed', 'processing'] }
        }
      },

      // Stage 2: Fast aggregation for key metrics
      {
        $facet: {
          // Revenue metrics
          revenueMetrics: [
            {
              $group: {
                _id: null,
                totalRevenue: { $sum: '$totalAmount' },
                orderCount: { $sum: 1 },
                avgOrderValue: { $avg: '$totalAmount' },
                maxOrderValue: { $max: '$totalAmount' }
              }
            }
          ],

          // Hourly breakdown
          hourlyBreakdown: [
            {
              $group: {
                _id: { hour: { $hour: '$createdAt' } },
                revenue: { $sum: '$totalAmount' },
                orders: { $sum: 1 }
              }
            },
            { $sort: { '_id.hour': 1 } }
          ],

          // Top products (by revenue)
          topProducts: [
            { $unwind: '$items' },
            {
              $group: {
                _id: '$items.productId',
                revenue: { $sum: { $multiply: ['$items.quantity', '$items.unitPrice'] } },
                quantity: { $sum: '$items.quantity' }
              }
            },
            { $sort: { revenue: -1 } },
            { $limit: 10 }
          ],

          // Geographic distribution
          geoDistribution: [
            {
              $group: {
                _id: '$shippingAddress.country',
                orders: { $sum: 1 },
                revenue: { $sum: '$totalAmount' }
              }
            },
            { $sort: { revenue: -1 } },
            { $limit: 20 }
          ],

          // Customer segments
          customerSegments: [
            {
              $group: {
                _id: {
                  segment: {
                    $switch: {
                      branches: [
                        { case: { $gte: ['$totalAmount', 500] }, then: 'premium' },
                        { case: { $gte: ['$totalAmount', 100] }, then: 'standard' }
                      ],
                      default: 'basic'
                    }
                  }
                },
                count: { $sum: 1 },
                revenue: { $sum: '$totalAmount' }
              }
            }
          ]
        }
      }
    ];

    const realTimeResults = await this.db.collection('orders').aggregate(
      realTimeDashboardPipeline,
      { maxTimeMS: 1000 } // 1 second timeout for real-time
    ).toArray();

    console.log('Real-time analytics completed');
    return realTimeResults[0];
  }

  async implementCustomerLifecycleAnalysis() {
    console.log('Building customer lifecycle analysis pipeline...');

    const lifecyclePipeline = [
      // Stage 1: Get all customers with their order history
      {
        $lookup: {
          from: 'orders',
          localField: '_id',
          foreignField: 'userId',
          as: 'orders',
          pipeline: [
            { $match: { status: 'completed' } },
            { $sort: { createdAt: 1 } },
            {
              $project: {
                createdAt: 1,
                totalAmount: 1,
                daysSinceRegistration: {
                  $divide: [
                    { $subtract: ['$createdAt', '$$ROOT.createdAt'] },
                    24 * 60 * 60 * 1000
                  ]
                }
              }
            }
          ]
        }
      },

      // Stage 2: Calculate lifecycle metrics
      {
        $addFields: {
          // Basic lifecycle metrics
          totalOrders: { $size: '$orders' },
          totalSpent: { $sum: '$orders.totalAmount' },
          avgOrderValue: { $avg: '$orders.totalAmount' },

          // Timing analysis
          firstOrderDate: { $min: '$orders.createdAt' },
          lastOrderDate: { $max: '$orders.createdAt' },
          customerLifespanDays: {
            $divide: [
              { $subtract: [{ $max: '$orders.createdAt' }, { $min: '$orders.createdAt' }] },
              24 * 60 * 60 * 1000
            ]
          },

          // Purchase intervals
          orderIntervals: {
            $map: {
              input: { $range: [1, { $size: '$orders' }] },
              as: 'idx',
              in: {
                $divide: [
                  {
                    $subtract: [
                      { $arrayElemAt: ['$orders.createdAt', '$$idx'] },
                      { $arrayElemAt: ['$orders.createdAt', { $subtract: ['$$idx', 1] }] }
                    ]
                  },
                  24 * 60 * 60 * 1000 // Convert to days
                ]
              }
            }
          },

          // CLV calculation (simplified)
          estimatedCLV: {
            $multiply: [
              { $avg: '$orders.totalAmount' }, // Average order value
              { $size: '$orders' }, // Order frequency
              {
                $cond: {
                  if: { $gt: [{ $size: '$orders' }, 1] },
                  then: {
                    $divide: [
                      365, // Days in year
                      { $avg: '$orderIntervals' } // Average days between orders
                    ]
                  },
                  else: 1
                }
              }
            ]
          }
        }
      },

      // Stage 3: Lifecycle stage classification
      {
        $addFields: {
          lifecycleStage: {
            $switch: {
              branches: [
                {
                  case: { $eq: ['$totalOrders', 1] },
                  then: 'new_customer'
                },
                {
                  case: {
                    $and: [
                      { $gte: ['$totalOrders', 2] },
                      { $lte: ['$totalOrders', 5] },
                      {
                        $gte: [
                          '$lastOrderDate',
                          new Date(Date.now() - 90 * 24 * 60 * 60 * 1000)
                        ]
                      }
                    ]
                  },
                  then: 'developing'
                },
                {
                  case: {
                    $and: [
                      { $gt: ['$totalOrders', 5] },
                      { $gte: ['$totalSpent', 500] },
                      {
                        $gte: [
                          '$lastOrderDate',
                          new Date(Date.now() - 180 * 24 * 60 * 60 * 1000)
                        ]
                      }
                    ]
                  },
                  then: 'loyal'
                },
                {
                  case: {
                    $and: [
                      { $gt: ['$totalOrders', 10] },
                      { $gte: ['$totalSpent', 2000] }
                    ]
                  },
                  then: 'champion'
                },
                {
                  case: {
                    $lt: [
                      '$lastOrderDate',
                      new Date(Date.now() - 365 * 24 * 60 * 60 * 1000)
                    ]
                  },
                  then: 'dormant'
                }
              ],
              default: 'at_risk'
            }
          },

          // Churn risk scoring
          churnRisk: {
            $let: {
              vars: {
                daysSinceLastOrder: {
                  $divide: [
                    { $subtract: [new Date(), '$lastOrderDate'] },
                    24 * 60 * 60 * 1000
                  ]
                },
                avgInterval: { $avg: '$orderIntervals' }
              },
              in: {
                $switch: {
                  branches: [
                    {
                      case: { $gt: ['$$daysSinceLastOrder', { $multiply: ['$$avgInterval', 3] }] },
                      then: 'high'
                    },
                    {
                      case: { $gt: ['$$daysSinceLastOrder', { $multiply: ['$$avgInterval', 2] }] },
                      then: 'medium'
                    }
                  ],
                  default: 'low'
                }
              }
            }
          }
        }
      },

      // Stage 4: Group by lifecycle stage for analysis
      {
        $group: {
          _id: {
            lifecycleStage: '$lifecycleStage',
            churnRisk: '$churnRisk'
          },

          customerCount: { $sum: 1 },
          totalRevenue: { $sum: '$totalSpent' },
          avgCLV: { $avg: '$estimatedCLV' },
          avgLifespan: { $avg: '$customerLifespanDays' },
          avgOrderFrequency: { $avg: { $avg: '$orderIntervals' } },

          // Statistical measures
          clvDistribution: {
            $push: {
              $bucket: {
                groupBy: '$estimatedCLV',
                boundaries: [0, 100, 500, 1000, 5000, 10000],
                default: 'high_value'
              }
            }
          }
        }
      },

      {
        $sort: { totalRevenue: -1 }
      }
    ];

    console.log('Executing customer lifecycle analysis...');
    const results = await this.db.collection('users').aggregate(lifecyclePipeline, {
      allowDiskUse: true,
      maxTimeMS: 30000
    }).toArray();

    return results;
  }

  async implementAdvancedTextAnalysis() {
    console.log('Building advanced text analysis pipeline...');

    // Advanced text analysis for reviews and feedback
    const textAnalysisPipeline = [
      // Stage 1: Match published reviews
      {
        $match: {
          status: 'published',
          reviewText: { $exists: true, $ne: '' }
        }
      },

      // Stage 2: Text processing and sentiment analysis
      {
        $addFields: {
          // Text metrics
          wordCount: {
            $size: {
              $split: [{ $trim: { input: '$reviewText' } }, ' ']
            }
          },

          // Sentiment indicators (simplified keyword approach)
          positiveWords: {
            $size: {
              $filter: {
                input: {
                  $split: [
                    { $toLower: '$reviewText' },
                    ' '
                  ]
                },
                cond: {
                  $in: [
                    '$$this',
                    ['excellent', 'great', 'amazing', 'love', 'perfect', 'awesome', 'fantastic', 'wonderful', 'outstanding', 'superb']
                  ]
                }
              }
            }
          },

          negativeWords: {
            $size: {
              $filter: {
                input: {
                  $split: [
                    { $toLower: '$reviewText' },
                    ' '
                  ]
                },
                cond: {
                  $in: [
                    '$$this',
                    ['terrible', 'awful', 'bad', 'horrible', 'worst', 'hate', 'disappointing', 'useless', 'broken', 'defective']
                  ]
                }
              }
            }
          },

          // Quality indicators
          qualityKeywords: {
            $size: {
              $filter: {
                input: {
                  $split: [
                    { $toLower: '$reviewText' },
                    ' '
                  ]
                },
                cond: {
                  $in: [
                    '$$this',
                    ['quality', 'durable', 'sturdy', 'well-made', 'premium', 'solid', 'reliable', 'long-lasting']
                  ]
                }
              }
            }
          },

          // Service indicators
          serviceKeywords: {
            $size: {
              $filter: {
                input: {
                  $split: [
                    { $toLower: '$reviewText' },
                    ' '
                  ]
                },
                cond: {
                  $in: [
                    '$$this',
                    ['service', 'support', 'shipping', 'delivery', 'customer', 'help', 'staff', 'team']
                  ]
                }
              }
            }
          }
        }
      },

      // Stage 3: Sentiment scoring
      {
        $addFields: {
          sentimentScore: {
            $subtract: ['$positiveWords', '$negativeWords']
          },

          sentimentCategory: {
            $switch: {
              branches: [
                {
                  case: { $gte: [{ $subtract: ['$positiveWords', '$negativeWords'] }, 2] },
                  then: 'very_positive'
                },
                {
                  case: { $gte: [{ $subtract: ['$positiveWords', '$negativeWords'] }, 1] },
                  then: 'positive'
                },
                {
                  case: { $lte: [{ $subtract: ['$positiveWords', '$negativeWords'] }, -2] },
                  then: 'very_negative'
                },
                {
                  case: { $lte: [{ $subtract: ['$positiveWords', '$negativeWords'] }, -1] },
                  then: 'negative'
                }
              ],
              default: 'neutral'
            }
          },

          reviewQuality: {
            $switch: {
              branches: [
                {
                  case: {
                    $and: [
                      { $gte: ['$wordCount', 50] },
                      { $gte: ['$rating', 4] },
                      { $gte: ['$helpfulVotes', 3] }
                    ]
                  },
                  then: 'high_quality'
                },
                {
                  case: {
                    $and: [
                      { $gte: ['$wordCount', 20] },
                      { $or: [{ $gte: ['$rating', 4] }, { $lte: ['$rating', 2] }] }
                    ]
                  },
                  then: 'moderate_quality'
                }
              ],
              default: 'low_quality'
            }
          }
        }
      },

      // Stage 4: Group by product for analysis
      {
        $group: {
          _id: '$productId',

          // Review volume metrics
          totalReviews: { $sum: 1 },
          avgRating: { $avg: '$rating' },
          ratingDistribution: {
            $push: {
              rating: '$rating',
              sentiment: '$sentimentCategory'
            }
          },

          // Text analysis metrics
          avgWordCount: { $avg: '$wordCount' },
          avgSentimentScore: { $avg: '$sentimentScore' },

          // Sentiment distribution
          veryPositive: {
            $sum: { $cond: [{ $eq: ['$sentimentCategory', 'very_positive'] }, 1, 0] }
          },
          positive: {
            $sum: { $cond: [{ $eq: ['$sentimentCategory', 'positive'] }, 1, 0] }
          },
          neutral: {
            $sum: { $cond: [{ $eq: ['$sentimentCategory', 'neutral'] }, 1, 0] }
          },
          negative: {
            $sum: { $cond: [{ $eq: ['$sentimentCategory', 'negative'] }, 1, 0] }
          },
          veryNegative: {
            $sum: { $cond: [{ $eq: ['$sentimentCategory', 'very_negative'] }, 1, 0] }
          },

          // Quality and service mentions
          qualityMentions: { $sum: '$qualityKeywords' },
          serviceMentions: { $sum: '$serviceKeywords' },

          // Review quality distribution
          highQualityReviews: {
            $sum: { $cond: [{ $eq: ['$reviewQuality', 'high_quality'] }, 1, 0] }
          },

          // Most helpful reviews
          topReviews: {
            $push: {
              $cond: {
                if: { $gte: ['$helpfulVotes', 5] },
                then: {
                  reviewId: '$_id',
                  rating: '$rating',
                  sentiment: '$sentimentCategory',
                  helpfulVotes: '$helpfulVotes',
                  wordCount: '$wordCount'
                },
                else: '$$REMOVE'
              }
            }
          }
        }
      },

      // Stage 5: Calculate comprehensive text metrics
      {
        $addFields: {
          // Overall sentiment ratio
          positiveRatio: {
            $divide: [
              { $add: ['$veryPositive', '$positive'] },
              '$totalReviews'
            ]
          },

          negativeRatio: {
            $divide: [
              { $add: ['$negative', '$veryNegative'] },
              '$totalReviews'
            ]
          },

          // Quality score
          qualityScore: {
            $add: [
              // Rating component (40%)
              { $multiply: [{ $divide: ['$avgRating', 5] }, 40] },

              // Sentiment component (30%)
              { $multiply: [{ $divide: [{ $add: ['$veryPositive', '$positive'] }, '$totalReviews'] }, 30] },

              // Review depth component (20%)
              { $multiply: [{ $min: [{ $divide: ['$avgWordCount', 100] }, 1] }, 20] },

              // Quality mentions component (10%)
              { $multiply: [{ $min: [{ $divide: ['$qualityMentions', '$totalReviews'] }, 1] }, 10] }
            ]
          },

          // Text analysis insights
          textInsights: {
            dominantSentiment: {
              $switch: {
                branches: [
                  { case: { $gte: ['$veryPositive', { $max: ['$positive', '$neutral', '$negative', '$veryNegative'] }] }, then: 'very_positive' },
                  { case: { $gte: ['$positive', { $max: ['$neutral', '$negative', '$veryNegative'] }] }, then: 'positive' },
                  { case: { $gte: ['$neutral', { $max: ['$negative', '$veryNegative'] }] }, then: 'neutral' },
                  { case: { $gte: ['$negative', '$veryNegative'] }, then: 'negative' }
                ],
                default: 'very_negative'
              }
            },

            reviewEngagement: {
              $divide: ['$highQualityReviews', '$totalReviews']
            },

            serviceAttention: {
              $divide: ['$serviceMentions', '$totalReviews']
            }
          }
        }
      },

      // Stage 6: Sort by quality score
      {
        $sort: { qualityScore: -1 }
      },

      // Stage 7: Lookup product information
      {
        $lookup: {
          from: 'products',
          localField: '_id',
          foreignField: '_id',
          as: 'product',
          pipeline: [
            {
              $project: {
                name: 1,
                category: 1,
                brand: 1,
                price: 1
              }
            }
          ]
        }
      },

      {
        $addFields: {
          productInfo: { $arrayElemAt: ['$product', 0] }
        }
      },

      {
        $project: {
          product: 0 // Remove array field
        }
      }
    ];

    console.log('Executing advanced text analysis...');
    const results = await this.db.collection('reviews').aggregate(textAnalysisPipeline, {
      allowDiskUse: true,
      maxTimeMS: 45000
    }).toArray();

    return results;
  }

  async monitorPipelinePerformance() {
    console.log('Monitoring aggregation pipeline performance...');

    const performanceMetrics = {
      collections: {},
      systemMetrics: {},
      recommendations: []
    };

    // Analyze recent aggregation operations
    try {
      const recentAggregations = await this.db.collection('system.profile').find({
        ts: { $gte: new Date(Date.now() - 24 * 60 * 60 * 1000) },
        'command.aggregate': { $exists: true },
        millis: { $gte: 1000 } // Operations taking more than 1 second
      }).sort({ millis: -1 }).limit(20).toArray();

      for (const aggOp of recentAggregations) {
        const analysis = {
          collection: aggOp.command.aggregate,
          duration: aggOp.millis,
          stages: aggOp.command.pipeline ? aggOp.command.pipeline.length : 0,
          allowDiskUse: aggOp.command.allowDiskUse || false,
          timestamp: aggOp.ts
        };

        if (!performanceMetrics.collections[analysis.collection]) {
          performanceMetrics.collections[analysis.collection] = {
            operations: [],
            avgDuration: 0,
            slowOperations: 0
          };
        }

        performanceMetrics.collections[analysis.collection].operations.push(analysis);

        if (analysis.duration > 5000) {
          performanceMetrics.collections[analysis.collection].slowOperations++;
        }
      }

      // Calculate averages and generate recommendations
      for (const [collection, metrics] of Object.entries(performanceMetrics.collections)) {
        const operations = metrics.operations;
        metrics.avgDuration = operations.reduce((sum, op) => sum + op.duration, 0) / operations.length;

        if (metrics.avgDuration > 10000) {
          performanceMetrics.recommendations.push({
            type: 'PERFORMANCE_WARNING',
            collection: collection,
            message: `Average aggregation duration (${metrics.avgDuration}ms) is high`,
            suggestions: [
              'Review pipeline stage ordering',
              'Add appropriate indexes',
              'Enable allowDiskUse for large datasets',
              'Consider data preprocessing'
            ]
          });
        }

        if (metrics.slowOperations > operations.length * 0.5) {
          performanceMetrics.recommendations.push({
            type: 'FREQUENT_SLOW_OPERATIONS',
            collection: collection,
            message: `${metrics.slowOperations} of ${operations.length} operations are slow`,
            suggestions: [
              'Optimize pipeline stages',
              'Review data volume and filtering',
              'Consider aggregation result caching'
            ]
          });
        }
      }

    } catch (error) {
      console.warn('Could not analyze aggregation performance:', error.message);
    }

    return performanceMetrics;
  }
}

SQL-Style Aggregation with QueryLeaf

QueryLeaf provides familiar SQL syntax for MongoDB aggregation operations:

-- QueryLeaf aggregation with SQL-familiar syntax

-- Complex analytical query with multiple aggregation levels
WITH customer_analytics AS (
  SELECT 
    u.country,
    u.registration_year,
    u.status,

    -- Customer metrics
    COUNT(*) as customer_count,
    AVG(u.total_spent) as avg_customer_value,
    SUM(u.total_spent) as total_revenue,

    -- Customer segmentation
    COUNT(CASE WHEN u.total_spent > 1000 THEN 1 END) as high_value_customers,
    COUNT(CASE WHEN u.total_spent BETWEEN 100 AND 1000 THEN 1 END) as medium_value_customers,
    COUNT(CASE WHEN u.total_spent < 100 THEN 1 END) as low_value_customers,

    -- Behavioral metrics
    AVG(u.order_count) as avg_orders_per_customer,
    AVG(DATEDIFF(CURRENT_DATE, u.last_order_date)) as avg_days_since_last_order,

    -- Geographic performance
    COUNT(DISTINCT u.state) as states_served,
    COUNT(DISTINCT u.city) as cities_served,

    -- Temporal analysis
    COUNT(CASE WHEN u.last_login >= CURRENT_DATE - INTERVAL '30 days' THEN 1 END) as active_users,
    COUNT(CASE WHEN u.last_login < CURRENT_DATE - INTERVAL '90 days' THEN 1 END) as inactive_users

  FROM users u
  WHERE u.created_at >= CURRENT_DATE - INTERVAL '2 years'
    AND u.status != 'deleted'
  GROUP BY u.country, u.registration_year, u.status
),

product_performance AS (
  SELECT 
    p.category,
    p.brand,

    -- Product metrics
    COUNT(*) as product_count,
    AVG(p.price) as avg_price,
    SUM(COALESCE(p.total_sales, 0)) as category_sales,

    -- Performance indicators
    AVG(p.rating) as avg_rating,
    COUNT(CASE WHEN p.rating >= 4.0 THEN 1 END) as highly_rated_products,
    COUNT(CASE WHEN p.stock_level < 10 THEN 1 END) as low_stock_products,

    -- Revenue analysis with complex calculations
    SUM(p.price * COALESCE(p.units_sold, 0)) as gross_revenue,
    AVG(p.price * COALESCE(p.units_sold, 0)) as avg_product_revenue,

    -- Market penetration
    COUNT(DISTINCT p.supplier_id) as supplier_diversity,

    -- Product lifecycle analysis
    COUNT(CASE WHEN p.created_at >= CURRENT_DATE - INTERVAL '6 months' THEN 1 END) as new_products,
    COUNT(CASE WHEN p.last_sold < CURRENT_DATE - INTERVAL '3 months' THEN 1 END) as stale_products,

    -- Statistical measures
    STDDEV(p.price) as price_variance,
    PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY p.price) as median_price,
    PERCENTILE_CONT(0.9) WITHIN GROUP (ORDER BY p.price) as price_p90

  FROM products p
  WHERE p.status = 'active'
  GROUP BY p.category, p.brand
  HAVING COUNT(*) >= 5  -- Categories with sufficient products
),

time_series_analysis AS (
  SELECT 
    DATE_TRUNC('month', o.created_at) as month,
    o.customer_country,

    -- Volume metrics
    COUNT(*) as order_count,
    SUM(o.total_amount) as monthly_revenue,
    COUNT(DISTINCT o.user_id) as unique_customers,

    -- Average metrics
    AVG(o.total_amount) as avg_order_value,
    AVG(JSON_LENGTH(o.items)) as avg_items_per_order,

    -- Growth calculations using window functions
    LAG(SUM(o.total_amount)) OVER (
      PARTITION BY o.customer_country 
      ORDER BY DATE_TRUNC('month', o.created_at)
    ) as prev_month_revenue,

    LAG(SUM(o.total_amount), 12) OVER (
      PARTITION BY o.customer_country 
      ORDER BY DATE_TRUNC('month', o.created_at)
    ) as same_month_last_year,

    -- Cumulative metrics
    SUM(SUM(o.total_amount)) OVER (
      PARTITION BY o.customer_country 
      ORDER BY DATE_TRUNC('month', o.created_at)
      ROWS UNBOUNDED PRECEDING
    ) as cumulative_revenue,

    -- Moving averages
    AVG(SUM(o.total_amount)) OVER (
      PARTITION BY o.customer_country 
      ORDER BY DATE_TRUNC('month', o.created_at)
      ROWS 2 PRECEDING
    ) as three_month_avg_revenue,

    -- Rankings
    RANK() OVER (
      PARTITION BY DATE_TRUNC('month', o.created_at)
      ORDER BY SUM(o.total_amount) DESC
    ) as monthly_country_rank

  FROM orders o
  WHERE o.status = 'completed'
    AND o.created_at >= CURRENT_DATE - INTERVAL '18 months'
  GROUP BY DATE_TRUNC('month', o.created_at), o.customer_country
),

advanced_text_analysis AS (
  SELECT 
    r.product_id,
    p.category,

    -- Review volume and ratings
    COUNT(*) as review_count,
    AVG(r.rating) as avg_rating,

    -- Sentiment analysis using text functions
    COUNT(CASE 
      WHEN LOWER(r.review_text) SIMILAR TO '%(excellent|great|amazing|love|perfect)%' 
      THEN 1 
    END) as positive_reviews,

    COUNT(CASE 
      WHEN LOWER(r.review_text) SIMILAR TO '%(terrible|awful|bad|horrible|hate)%' 
      THEN 1 
    END) as negative_reviews,

    -- Text quality metrics
    AVG(LENGTH(r.review_text)) as avg_review_length,
    COUNT(CASE WHEN LENGTH(r.review_text) > 100 THEN 1 END) as detailed_reviews,

    -- Helpfulness metrics
    AVG(r.helpful_votes) as avg_helpfulness,
    COUNT(CASE WHEN r.helpful_votes >= 5 THEN 1 END) as highly_helpful_reviews,

    -- Topic analysis using keyword matching
    COUNT(CASE 
      WHEN LOWER(r.review_text) SIMILAR TO '%(quality|durable|sturdy|well-made)%' 
      THEN 1 
    END) as quality_mentions,

    COUNT(CASE 
      WHEN LOWER(r.review_text) SIMILAR TO '%(shipping|delivery|fast|quick)%' 
      THEN 1 
    END) as shipping_mentions,

    -- Rating distribution analysis
    JSON_OBJECT(
      'rating_5', COUNT(CASE WHEN r.rating = 5 THEN 1 END),
      'rating_4', COUNT(CASE WHEN r.rating = 4 THEN 1 END),
      'rating_3', COUNT(CASE WHEN r.rating = 3 THEN 1 END),
      'rating_2', COUNT(CASE WHEN r.rating = 2 THEN 1 END),
      'rating_1', COUNT(CASE WHEN r.rating = 1 THEN 1 END)
    ) as rating_distribution

  FROM reviews r
  JOIN products p ON r.product_id = p.id
  WHERE r.status = 'published'
    AND r.created_at >= CURRENT_DATE - INTERVAL '1 year'
  GROUP BY r.product_id, p.category
  HAVING COUNT(*) >= 10  -- Products with sufficient reviews
)

-- Final comprehensive analysis combining all CTEs
SELECT 
  ca.country,
  ca.customer_count,
  ca.total_revenue,
  ROUND(ca.avg_customer_value, 2) as avg_customer_ltv,

  -- Customer segmentation percentages
  ROUND((ca.high_value_customers / ca.customer_count::float) * 100, 1) as high_value_pct,
  ROUND((ca.medium_value_customers / ca.customer_count::float) * 100, 1) as medium_value_pct,
  ROUND((ca.low_value_customers / ca.customer_count::float) * 100, 1) as low_value_pct,

  -- Activity metrics
  ROUND((ca.active_users / ca.customer_count::float) * 100, 1) as active_user_pct,
  ROUND(ca.avg_orders_per_customer, 1) as avg_orders_per_customer,

  -- Product ecosystem metrics
  (SELECT COUNT(DISTINCT pp.category) 
   FROM product_performance pp) as total_categories,

  (SELECT AVG(pp.avg_rating) 
   FROM product_performance pp) as overall_product_rating,

  -- Time series insights (latest month data)
  (SELECT tsa.monthly_revenue 
   FROM time_series_analysis tsa 
   WHERE tsa.customer_country = ca.country 
   ORDER BY tsa.month DESC 
   LIMIT 1) as latest_month_revenue,

  -- Growth rate calculation
  (SELECT 
     CASE 
       WHEN tsa.prev_month_revenue > 0 THEN
         ROUND(((tsa.monthly_revenue - tsa.prev_month_revenue) / tsa.prev_month_revenue * 100), 2)
       ELSE NULL
     END
   FROM time_series_analysis tsa 
   WHERE tsa.customer_country = ca.country 
   ORDER BY tsa.month DESC 
   LIMIT 1) as mom_growth_rate,

  -- Year over year growth
  (SELECT 
     CASE 
       WHEN tsa.same_month_last_year > 0 THEN
         ROUND(((tsa.monthly_revenue - tsa.same_month_last_year) / tsa.same_month_last_year * 100), 2)
       ELSE NULL
     END
   FROM time_series_analysis tsa 
   WHERE tsa.customer_country = ca.country 
   ORDER BY tsa.month DESC 
   LIMIT 1) as yoy_growth_rate,

  -- Text sentiment analysis
  (SELECT 
     ROUND(AVG(ata.positive_reviews / ata.review_count::float) * 100, 1)
   FROM advanced_text_analysis ata) as avg_positive_sentiment_pct,

  -- Quality perception
  (SELECT 
     ROUND(AVG(ata.quality_mentions / ata.review_count::float) * 100, 1)
   FROM advanced_text_analysis ata) as quality_mention_pct,

  -- Strategic classification
  CASE 
    WHEN ca.total_revenue > 100000 AND ca.high_value_customers > ca.customer_count * 0.2 THEN 'key_market'
    WHEN ca.total_revenue > 50000 AND ca.active_users > ca.customer_count * 0.6 THEN 'growth_market'
    WHEN ca.inactive_users > ca.customer_count * 0.5 THEN 'retention_focus'
    ELSE 'development_market'
  END as market_classification,

  -- Opportunity scoring
  (ca.total_revenue * 0.4 + 
   ca.customer_count * 10 * 0.3 + 
   ca.active_users * 15 * 0.3) as opportunity_score

FROM customer_analytics ca
WHERE ca.customer_count >= 50  -- Markets with sufficient size
ORDER BY ca.total_revenue DESC, ca.customer_count DESC;

-- Real-time dashboard query with faceted aggregation
SELECT 
  -- Today's metrics
  'today_metrics' as facet,
  JSON_OBJECT(
    'orders', COUNT(CASE WHEN o.created_at >= CURRENT_DATE THEN 1 END),
    'revenue', SUM(CASE WHEN o.created_at >= CURRENT_DATE THEN o.total_amount ELSE 0 END),
    'customers', COUNT(DISTINCT CASE WHEN o.created_at >= CURRENT_DATE THEN o.user_id END),
    'avg_order_value', AVG(CASE WHEN o.created_at >= CURRENT_DATE THEN o.total_amount END)
  ) as metrics
FROM orders o
WHERE o.status = 'completed' 
  AND o.created_at >= CURRENT_DATE - INTERVAL '1 day'

UNION ALL

-- Hourly breakdown for today
SELECT 
  'hourly_breakdown' as facet,
  JSON_OBJECT(
    'data', JSON_ARRAYAGG(
      JSON_OBJECT(
        'hour', EXTRACT(HOUR FROM o.created_at),
        'orders', COUNT(*),
        'revenue', SUM(o.total_amount)
      )
    )
  ) as metrics
FROM orders o
WHERE o.status = 'completed'
  AND o.created_at >= CURRENT_DATE
GROUP BY EXTRACT(HOUR FROM o.created_at)

UNION ALL

-- Top performing products today  
SELECT 
  'top_products' as facet,
  JSON_OBJECT(
    'data', JSON_ARRAYAGG(
      JSON_OBJECT(
        'product_id', oi.product_id,
        'revenue', SUM(oi.quantity * oi.unit_price),
        'units_sold', SUM(oi.quantity)
      )
    )
  ) as metrics
FROM orders o
JOIN JSON_TABLE(o.items, '$[*]' COLUMNS (
  product_id VARCHAR(50) PATH '$.productId',
  quantity INT PATH '$.quantity', 
  unit_price DECIMAL(10,2) PATH '$.unitPrice'
)) oi ON TRUE
WHERE o.status = 'completed'
  AND o.created_at >= CURRENT_DATE
GROUP BY oi.product_id
ORDER BY SUM(oi.quantity * oi.unit_price) DESC
LIMIT 10;

-- QueryLeaf provides comprehensive aggregation capabilities:
-- 1. Complex multi-level aggregations with CTEs and subqueries
-- 2. Advanced window functions for time-series analysis and trends
-- 3. JSON aggregation functions for flexible data processing
-- 4. Text analysis capabilities with pattern matching and sentiment analysis
-- 5. Statistical functions including percentiles and standard deviation
-- 6. Faceted queries for dashboard and real-time analytics
-- 7. Flexible grouping and segmentation with conditional logic
-- 8. Performance optimization with proper indexing hints
-- 9. Real-time metrics calculation with temporal filtering
-- 10. Integration with MongoDB's native aggregation framework optimizations

Best Practices for Aggregation Pipeline Optimization

Pipeline Design Guidelines

Essential principles for optimal MongoDB aggregation performance:

  1. Early Filtering: Place $match stages as early as possible to reduce dataset size
  2. Index Utilization: Design pipelines to leverage existing indexes effectively
  3. Memory Management: Use allowDiskUse for large datasets and monitor memory usage
  4. Stage Ordering: Follow optimal stage ordering principles for performance
  5. Projection Early: Use $project stages to reduce document size in pipeline
  6. Batch Size Optimization: Configure appropriate cursor batch sizes for large results

Production Performance Optimization

Optimize MongoDB aggregation pipelines for production workloads:

  1. Performance Monitoring: Implement continuous pipeline performance monitoring
  2. Result Caching: Cache aggregation results for frequently executed pipelines
  3. Incremental Processing: Design incremental aggregation patterns for large datasets
  4. Resource Management: Monitor CPU, memory, and disk usage during aggregation
  5. Query Profiling: Use MongoDB profiler to identify aggregation bottlenecks
  6. Parallel Processing: Leverage sharding and replica sets for parallel aggregation

Conclusion

MongoDB's advanced aggregation framework provides comprehensive data processing capabilities that eliminate the limitations and complexity of traditional relational database aggregation approaches. The flexible pipeline architecture supports sophisticated analytics, real-time processing, and complex transformations while maintaining optimal performance at scale.

Key MongoDB Aggregation benefits include:

  • Flexible Pipeline Architecture: Multi-stage processing with optimizable stage ordering and memory management
  • Rich Analytical Capabilities: Advanced operators supporting complex calculations, statistical analysis, and data transformations
  • Performance Optimization: Built-in query optimization, index integration, and resource management
  • Real-time Processing: Support for real-time analytics and streaming aggregation operations
  • Scalable Architecture: Pipeline execution across replica sets and sharded clusters
  • SQL-Familiar Interface: QueryLeaf integration providing familiar aggregation syntax and patterns

Whether you're building real-time dashboards, conducting complex business intelligence analysis, or implementing sophisticated data processing workflows, MongoDB's aggregation framework with QueryLeaf's familiar SQL interface provides the foundation for high-performance analytical operations.

QueryLeaf Integration: QueryLeaf automatically optimizes MongoDB aggregation pipelines while providing SQL-familiar aggregation syntax, window functions, and analytical capabilities. Complex data transformations, statistical analysis, and real-time analytics are seamlessly handled through familiar SQL constructs, making sophisticated data processing both powerful and accessible to SQL-oriented development teams.

The combination of native MongoDB aggregation capabilities with SQL-style operations makes MongoDB an ideal platform for applications requiring both flexible data processing and familiar analytical patterns, ensuring your applications can handle complex analytical workloads while remaining maintainable and performant as they scale.

MongoDB Query Optimization and Explain Plans: Advanced Performance Analysis for High-Performance Database Operations

Database performance optimization is critical for applications that demand fast response times and efficient resource utilization. Poor query performance can lead to degraded user experience, increased infrastructure costs, and system bottlenecks that become increasingly problematic as data volumes and user loads grow.

MongoDB's sophisticated query optimizer and explain plan system provide comprehensive insights into query execution strategies, enabling developers and database administrators to identify performance bottlenecks, optimize index usage, and fine-tune queries for maximum efficiency. Unlike traditional database systems with limited query analysis tools, MongoDB's explain functionality offers detailed execution statistics, index usage patterns, and optimization recommendations that support both development and production performance tuning.

The Traditional Query Analysis Challenge

Conventional database systems often provide limited query analysis capabilities that make performance optimization difficult:

-- Traditional PostgreSQL query analysis with limited optimization insights

-- Basic EXPLAIN output with limited actionable information
EXPLAIN ANALYZE
SELECT 
  u.user_id,
  u.email,
  u.first_name,
  u.last_name,
  u.created_at,
  COUNT(o.order_id) as order_count,
  SUM(o.total_amount) as total_spent,
  AVG(o.total_amount) as avg_order_value,
  MAX(o.created_at) as last_order_date
FROM users u
LEFT JOIN orders o ON u.user_id = o.user_id
WHERE u.status = 'active'
  AND u.country IN ('US', 'CA', 'UK')
  AND u.created_at >= '2023-01-01'
  AND (o.status = 'completed' OR o.status IS NULL)
GROUP BY u.user_id, u.email, u.first_name, u.last_name, u.created_at
HAVING COUNT(o.order_id) > 0 OR u.created_at >= '2024-01-01'
ORDER BY total_spent DESC, order_count DESC
LIMIT 100;

-- PostgreSQL EXPLAIN output (simplified representation):
--
-- Limit  (cost=15234.45..15234.70 rows=100 width=64) (actual time=245.123..245.167 rows=100 loops=1)
--   ->  Sort  (cost=15234.45..15489.78 rows=102133 width=64) (actual time=245.121..245.138 rows=100 loops=1)
--         Sort Key: (sum(o.total_amount)) DESC, (count(o.order_id)) DESC  
--         Sort Method: top-N heapsort  Memory: 40kB
--         ->  HashAggregate  (cost=11234.56..12456.89 rows=102133 width=64) (actual time=198.456..223.789 rows=45678 loops=1)
--               Group Key: u.user_id, u.email, u.first_name, u.last_name, u.created_at
--               ->  Hash Left Join  (cost=2345.67..8901.23 rows=345678 width=48) (actual time=12.456..89.123 rows=123456 loops=1)
--                     Hash Cond: (u.user_id = o.user_id)
--                     ->  Bitmap Heap Scan on users u  (cost=234.56..1789.45 rows=12345 width=32) (actual time=3.456..15.789 rows=8901 loops=1)
--                           Recheck Cond: ((status = 'active'::text) AND (country = ANY ('{US,CA,UK}'::text[])) AND (created_at >= '2023-01-01'::date))
--                           Heap Blocks: exact=234
--                           ->  BitmapOr  (cost=234.56..234.56 rows=12345 width=0) (actual time=2.890..2.891 rows=0 loops=1)
--                                 ->  Bitmap Index Scan on idx_users_status  (cost=0.00..78.12 rows=4567 width=0) (actual time=0.890..0.890 rows=3456 loops=1)
--                                       Index Cond: (status = 'active'::text)
--                     ->  Hash  (cost=1890.45..1890.45 rows=17890 width=24) (actual time=8.567..8.567 rows=14567 loops=1)
--                           Buckets: 32768  Batches: 1  Memory Usage: 798kB
--                           ->  Seq Scan on orders o  (cost=0.00..1890.45 rows=17890 width=24) (actual time=0.123..5.456 rows=14567 loops=1)
--                                 Filter: ((status = 'completed'::text) OR (status IS NULL))
--                                 Rows Removed by Filter: 3456
-- Planning Time: 2.456 ms
-- Execution Time: 245.678 ms

-- Problems with traditional PostgreSQL EXPLAIN:
-- 1. Complex output format that's difficult to interpret quickly
-- 2. Limited insights into index selection reasoning and alternatives
-- 3. No built-in recommendations for performance improvements
-- 4. Difficult to compare execution plans across different query variations
-- 5. Limited visibility into buffer usage, I/O patterns, and memory allocation
-- 6. No integration with query optimization recommendations or automated tuning
-- 7. Verbose output that makes it hard to identify key performance bottlenecks
-- 8. Limited historical explain plan tracking and performance trend analysis

-- Alternative PostgreSQL analysis approaches
-- Using pg_stat_statements for query analysis (requires extension)
SELECT 
  query,
  calls,
  total_time,
  mean_time,
  rows,
  100.0 * shared_blks_hit / nullif(shared_blks_hit + shared_blks_read, 0) AS hit_percent
FROM pg_stat_statements 
WHERE query LIKE '%users%orders%'
ORDER BY mean_time DESC
LIMIT 10;

-- Problems with pg_stat_statements:
-- - Requires additional configuration and extensions
-- - Limited detail about specific execution patterns
-- - No real-time optimization recommendations
-- - Difficult correlation between query patterns and index usage
-- - Limited integration with application performance monitoring

-- MySQL approach (even more limited)
EXPLAIN FORMAT=JSON
SELECT u.user_id, u.email, COUNT(o.order_id) as orders
FROM users u 
LEFT JOIN orders o ON u.user_id = o.user_id 
WHERE u.status = 'active'
GROUP BY u.user_id, u.email;

-- MySQL EXPLAIN limitations:
-- {
--   "query_block": {
--     "select_id": 1,
--     "cost_info": {
--       "query_cost": "1234.56"
--     },
--     "grouping_operation": {
--       "using_filesort": false,
--       "nested_loop": [
--         {
--           "table": {
--             "table_name": "u",
--             "access_type": "range",
--             "possible_keys": ["idx_status"],
--             "key": "idx_status",
--             "used_key_parts": ["status"],
--             "key_length": "767",
--             "rows_examined_per_scan": 1000,
--             "rows_produced_per_join": 1000,
--             "cost_info": {
--               "read_cost": "200.00",
--               "eval_cost": "100.00",
--               "prefix_cost": "300.00",
--               "data_read_per_join": "64K"
--             }
--           }
--         }
--       ]
--     }
--   }
-- }

-- MySQL EXPLAIN problems:
-- - Very basic cost model with limited accuracy
-- - No detailed execution statistics or actual vs estimated comparisons
-- - Limited index optimization recommendations  
-- - Basic JSON format that's difficult to analyze programmatically
-- - No integration with performance monitoring or automated optimization
-- - Limited support for complex query patterns and aggregations
-- - Minimal historical performance tracking capabilities

MongoDB provides comprehensive query analysis and optimization tools:

// MongoDB Advanced Query Optimization - comprehensive explain plans and performance analysis
const { MongoClient } = require('mongodb');

const client = new MongoClient('mongodb://localhost:27017');
const db = client.db('ecommerce_analytics');

// Advanced query optimization and explain plan analysis system
class MongoQueryOptimizer {
  constructor(db) {
    this.db = db;
    this.collections = {
      users: db.collection('users'),
      orders: db.collection('orders'),
      products: db.collection('products'),
      analytics: db.collection('analytics')
    };

    // Performance analysis configuration
    this.performanceTargets = {
      maxExecutionTimeMs: 100,
      maxDocsExamined: 10000,
      minIndexHitRate: 0.95,
      maxMemoryUsageMB: 32
    };

    this.optimizationStrategies = new Map();
    this.explainCache = new Map();
  }

  async analyzeQueryPerformance(collection, pipeline, options = {}) {
    console.log('Analyzing query performance with comprehensive explain plans...');

    const {
      verbosity = 'executionStats', // 'queryPlanner', 'executionStats', 'allPlansExecution'
      includeRecommendations = true,
      compareAlternatives = true,
      trackMetrics = true
    } = options;

    // Get the collection reference
    const coll = typeof collection === 'string' ? this.collections[collection] : collection;

    // Execute explain with comprehensive analysis
    const explainResult = await this.performComprehensiveExplain(coll, pipeline, verbosity);

    // Analyze explain plan for optimization opportunities
    const analysis = this.analyzeExplainPlan(explainResult);

    // Generate optimization recommendations
    const recommendations = includeRecommendations ? 
      await this.generateOptimizationRecommendations(coll, pipeline, explainResult, analysis) : [];

    // Compare with alternative query strategies
    const alternatives = compareAlternatives ? 
      await this.generateQueryAlternatives(coll, pipeline, explainResult) : [];

    // Track performance metrics for historical analysis
    if (trackMetrics) {
      await this.recordPerformanceMetrics(coll.collectionName, pipeline, explainResult, analysis);
    }

    const performanceReport = {
      query: {
        collection: coll.collectionName,
        pipeline: pipeline,
        timestamp: new Date()
      },

      execution: {
        totalTimeMs: explainResult.executionStats?.executionTimeMillis || 0,
        totalDocsExamined: explainResult.executionStats?.totalDocsExamined || 0,
        totalDocsReturned: explainResult.executionStats?.totalDocsReturned || 0,
        executionSuccess: explainResult.executionStats?.executionSuccess || false,
        indexesUsed: this.extractIndexesUsed(explainResult),
        memoryUsage: this.calculateMemoryUsage(explainResult)
      },

      performance: {
        efficiency: this.calculateQueryEfficiency(explainResult),
        indexHitRate: this.calculateIndexHitRate(explainResult),
        selectivity: this.calculateSelectivity(explainResult),
        performanceGrade: this.assignPerformanceGrade(explainResult),
        bottlenecks: analysis.bottlenecks,
        strengths: analysis.strengths
      },

      optimization: {
        recommendations: recommendations,
        alternatives: alternatives,
        estimatedImprovement: this.estimateOptimizationImpact(recommendations),
        prioritizedActions: this.prioritizeOptimizations(recommendations)
      },

      explainDetails: explainResult
    };

    console.log(`Query analysis completed - Performance Grade: ${performanceReport.performance.performanceGrade}`);
    console.log(`Execution Time: ${performanceReport.execution.totalTimeMs}ms`);
    console.log(`Documents Examined: ${performanceReport.execution.totalDocsExamined}`);
    console.log(`Documents Returned: ${performanceReport.execution.totalDocsReturned}`);
    console.log(`Index Hit Rate: ${(performanceReport.performance.indexHitRate * 100).toFixed(1)}%`);

    return performanceReport;
  }

  async performComprehensiveExplain(collection, pipeline, verbosity) {
    console.log(`Executing explain with verbosity: ${verbosity}`);

    try {
      // Handle different query types
      if (Array.isArray(pipeline)) {
        // Aggregation pipeline
        const cursor = collection.aggregate(pipeline);
        return await cursor.explain(verbosity);
      } else if (typeof pipeline === 'object' && pipeline.find) {
        // Find query
        const cursor = collection.find(pipeline.find, pipeline.options || {});
        if (pipeline.sort) cursor.sort(pipeline.sort);
        if (pipeline.limit) cursor.limit(pipeline.limit);
        if (pipeline.skip) cursor.skip(pipeline.skip);

        return await cursor.explain(verbosity);
      } else {
        // Simple find query
        const cursor = collection.find(pipeline);
        return await cursor.explain(verbosity);
      }
    } catch (error) {
      console.error('Explain execution failed:', error);
      return {
        error: error.message,
        executionSuccess: false,
        executionTimeMillis: 0
      };
    }
  }

  analyzeExplainPlan(explainResult) {
    console.log('Analyzing explain plan for performance insights...');

    const analysis = {
      queryType: this.identifyQueryType(explainResult),
      executionPattern: this.analyzeExecutionPattern(explainResult),
      indexUsage: this.analyzeIndexUsage(explainResult),
      bottlenecks: [],
      strengths: [],
      riskFactors: [],
      optimizationOpportunities: []
    };

    // Identify performance bottlenecks
    analysis.bottlenecks = this.identifyBottlenecks(explainResult);

    // Identify query strengths
    analysis.strengths = this.identifyStrengths(explainResult);

    // Identify risk factors
    analysis.riskFactors = this.identifyRiskFactors(explainResult);

    // Identify optimization opportunities
    analysis.optimizationOpportunities = this.identifyOptimizationOpportunities(explainResult);

    return analysis;
  }

  identifyBottlenecks(explainResult) {
    const bottlenecks = [];
    const stats = explainResult.executionStats;

    if (!stats) return bottlenecks;

    // Collection scan bottleneck
    if (this.hasCollectionScan(explainResult)) {
      bottlenecks.push({
        type: 'COLLECTION_SCAN',
        severity: 'HIGH',
        description: 'Query performs collection scan instead of using index',
        impact: 'High CPU and I/O usage, poor scalability',
        docsExamined: stats.totalDocsExamined
      });
    }

    // Poor index selectivity
    const selectivity = this.calculateSelectivity(explainResult);
    if (selectivity < 0.1) {
      bottlenecks.push({
        type: 'POOR_SELECTIVITY',
        severity: 'MEDIUM',
        description: 'Index selectivity is poor, examining many unnecessary documents',
        impact: 'Increased I/O and processing time',
        selectivity: selectivity,
        docsExamined: stats.totalDocsExamined,
        docsReturned: stats.totalDocsReturned
      });
    }

    // High execution time
    if (stats.executionTimeMillis > this.performanceTargets.maxExecutionTimeMs) {
      bottlenecks.push({
        type: 'HIGH_EXECUTION_TIME',
        severity: 'HIGH',
        description: 'Query execution time exceeds performance target',
        impact: 'User experience degradation, resource contention',
        executionTime: stats.executionTimeMillis,
        target: this.performanceTargets.maxExecutionTimeMs
      });
    }

    // Sort without index
    if (this.hasSortWithoutIndex(explainResult)) {
      bottlenecks.push({
        type: 'SORT_WITHOUT_INDEX',
        severity: 'MEDIUM',
        description: 'Sort operation performed in memory without index support',
        impact: 'High memory usage, slower sort performance',
        memoryUsage: this.calculateSortMemoryUsage(explainResult)
      });
    }

    // Large result set without limit
    if (stats.totalDocsReturned > 1000 && !this.hasLimit(explainResult)) {
      bottlenecks.push({
        type: 'LARGE_RESULT_SET',
        severity: 'MEDIUM',
        description: 'Query returns large number of documents without limit',
        impact: 'High memory usage, network overhead',
        docsReturned: stats.totalDocsReturned
      });
    }

    return bottlenecks;
  }

  identifyStrengths(explainResult) {
    const strengths = [];
    const stats = explainResult.executionStats;

    if (!stats) return strengths;

    // Efficient index usage
    if (this.hasEfficientIndexUsage(explainResult)) {
      strengths.push({
        type: 'EFFICIENT_INDEX_USAGE',
        description: 'Query uses indexes efficiently with good selectivity',
        indexesUsed: this.extractIndexesUsed(explainResult),
        selectivity: this.calculateSelectivity(explainResult)
      });
    }

    // Fast execution time
    if (stats.executionTimeMillis < this.performanceTargets.maxExecutionTimeMs * 0.5) {
      strengths.push({
        type: 'FAST_EXECUTION',
        description: 'Query executes well below performance targets',
        executionTime: stats.executionTimeMillis,
        target: this.performanceTargets.maxExecutionTimeMs
      });
    }

    // Covered query
    if (this.isCoveredQuery(explainResult)) {
      strengths.push({
        type: 'COVERED_QUERY',
        description: 'Query is covered entirely by index, no document retrieval needed',
        indexesUsed: this.extractIndexesUsed(explainResult)
      });
    }

    // Good result set size management
    if (stats.totalDocsReturned < 100 || this.hasLimit(explainResult)) {
      strengths.push({
        type: 'APPROPRIATE_RESULT_SIZE',
        description: 'Query returns appropriate number of documents',
        docsReturned: stats.totalDocsReturned,
        hasLimit: this.hasLimit(explainResult)
      });
    }

    return strengths;
  }

  async generateOptimizationRecommendations(collection, pipeline, explainResult, analysis) {
    console.log('Generating optimization recommendations...');

    const recommendations = [];

    // Index recommendations based on bottlenecks
    for (const bottleneck of analysis.bottlenecks) {
      switch (bottleneck.type) {
        case 'COLLECTION_SCAN':
          recommendations.push({
            type: 'CREATE_INDEX',
            priority: 'HIGH',
            description: 'Create index to eliminate collection scan',
            action: await this.suggestIndexForQuery(collection, pipeline, explainResult),
            estimatedImprovement: '80-95% reduction in execution time',
            implementation: 'Create compound index on filtered and sorted fields'
          });
          break;

        case 'POOR_SELECTIVITY':
          recommendations.push({
            type: 'IMPROVE_INDEX_SELECTIVITY',
            priority: 'MEDIUM',
            description: 'Improve index selectivity with partial index or compound index',
            action: await this.suggestSelectivityImprovement(collection, pipeline, explainResult),
            estimatedImprovement: '30-60% reduction in documents examined',
            implementation: 'Add partial filter or reorganize compound index field order'
          });
          break;

        case 'SORT_WITHOUT_INDEX':
          recommendations.push({
            type: 'INDEX_FOR_SORT',
            priority: 'MEDIUM',
            description: 'Create or modify index to support sort operation',
            action: await this.suggestSortIndex(collection, pipeline, explainResult),
            estimatedImprovement: '50-80% reduction in memory usage and sort time',
            implementation: 'Include sort fields in compound index following ESR pattern'
          });
          break;

        case 'LARGE_RESULT_SET':
          recommendations.push({
            type: 'LIMIT_RESULT_SET',
            priority: 'LOW',
            description: 'Add pagination or result limiting to reduce memory usage',
            action: 'Add $limit stage or implement pagination',
            estimatedImprovement: 'Reduced memory usage and network overhead',
            implementation: 'Implement cursor-based pagination or reasonable limits'
          });
          break;
      }
    }

    // Query restructuring recommendations
    const structuralRecs = await this.suggestQueryRestructuring(collection, pipeline, explainResult);
    recommendations.push(...structuralRecs);

    // Aggregation pipeline optimization
    if (Array.isArray(pipeline)) {
      const pipelineRecs = await this.suggestPipelineOptimizations(pipeline, explainResult);
      recommendations.push(...pipelineRecs);
    }

    return recommendations;
  }

  async generateQueryAlternatives(collection, pipeline, explainResult) {
    console.log('Generating alternative query strategies...');

    const alternatives = [];

    // Test different index hints
    const indexAlternatives = await this.testIndexAlternatives(collection, pipeline);
    alternatives.push(...indexAlternatives);

    // Test different aggregation pipeline orders
    if (Array.isArray(pipeline)) {
      const pipelineAlternatives = await this.testPipelineAlternatives(collection, pipeline);
      alternatives.push(...pipelineAlternatives);
    }

    // Test query restructuring alternatives
    const structuralAlternatives = await this.testStructuralAlternatives(collection, pipeline);
    alternatives.push(...structuralAlternatives);

    return alternatives;
  }

  async suggestIndexForQuery(collection, pipeline, explainResult) {
    // Analyze query pattern to suggest optimal index
    const queryFields = this.extractQueryFields(pipeline);
    const sortFields = this.extractSortFields(pipeline);

    const indexSuggestion = {
      fields: {},
      options: {}
    };

    // Apply ESR (Equality, Sort, Range) pattern
    const equalityFields = queryFields.equality || [];
    const rangeFields = queryFields.range || [];

    // Add equality fields first
    equalityFields.forEach(field => {
      indexSuggestion.fields[field] = 1;
    });

    // Add sort fields
    if (sortFields) {
      Object.entries(sortFields).forEach(([field, direction]) => {
        indexSuggestion.fields[field] = direction;
      });
    }

    // Add range fields last
    rangeFields.forEach(field => {
      if (!indexSuggestion.fields[field]) {
        indexSuggestion.fields[field] = 1;
      }
    });

    // Suggest partial index if selective filters present
    if (queryFields.selective && queryFields.selective.length > 0) {
      indexSuggestion.options.partialFilterExpression = this.buildPartialFilter(queryFields.selective);
    }

    return {
      indexSpec: indexSuggestion.fields,
      indexOptions: indexSuggestion.options,
      createCommand: `db.${collection.collectionName}.createIndex(${JSON.stringify(indexSuggestion.fields)}, ${JSON.stringify(indexSuggestion.options)})`,
      explanation: this.explainIndexSuggestion(indexSuggestion, queryFields, sortFields)
    };
  }

  calculateQueryEfficiency(explainResult) {
    const stats = explainResult.executionStats;
    if (!stats) return 0;

    const docsExamined = stats.totalDocsExamined || 0;
    const docsReturned = stats.totalDocsReturned || 0;

    if (docsExamined === 0) return 1;

    return Math.min(1, docsReturned / docsExamined);
  }

  calculateIndexHitRate(explainResult) {
    if (this.hasCollectionScan(explainResult)) return 0;

    const indexUsage = this.analyzeIndexUsage(explainResult);
    return indexUsage.effectiveness || 0.5;
  }

  calculateSelectivity(explainResult) {
    const stats = explainResult.executionStats;
    if (!stats) return 0;

    const docsExamined = stats.totalDocsExamined || 0;
    const docsReturned = stats.totalDocsReturned || 0;

    if (docsExamined === 0) return 1;

    return docsReturned / docsExamined;
  }

  assignPerformanceGrade(explainResult) {
    const efficiency = this.calculateQueryEfficiency(explainResult);
    const indexHitRate = this.calculateIndexHitRate(explainResult);
    const stats = explainResult.executionStats;
    const executionTime = stats?.executionTimeMillis || 0;

    let score = 0;

    // Efficiency scoring (40% weight)
    if (efficiency >= 0.9) score += 40;
    else if (efficiency >= 0.7) score += 30;
    else if (efficiency >= 0.5) score += 20;
    else if (efficiency >= 0.2) score += 10;

    // Index usage scoring (35% weight)
    if (indexHitRate >= 0.95) score += 35;
    else if (indexHitRate >= 0.8) score += 25;
    else if (indexHitRate >= 0.5) score += 15;
    else if (indexHitRate >= 0.2) score += 5;

    // Execution time scoring (25% weight)
    if (executionTime <= 50) score += 25;
    else if (executionTime <= 100) score += 20;
    else if (executionTime <= 250) score += 15;
    else if (executionTime <= 500) score += 10;
    else if (executionTime <= 1000) score += 5;

    // Convert to letter grade
    if (score >= 85) return 'A';
    else if (score >= 75) return 'B';
    else if (score >= 65) return 'C';
    else if (score >= 50) return 'D';
    else return 'F';
  }

  // Helper methods for detailed analysis

  hasCollectionScan(explainResult) {
    return this.findStageInPlan(explainResult, 'COLLSCAN') !== null;
  }

  hasSortWithoutIndex(explainResult) {
    const sortStage = this.findStageInPlan(explainResult, 'SORT');
    return sortStage !== null && !sortStage.inputStage?.stage?.includes('IXSCAN');
  }

  hasLimit(explainResult) {
    return this.findStageInPlan(explainResult, 'LIMIT') !== null;
  }

  isCoveredQuery(explainResult) {
    // Check if query is covered by examining projection and index keys
    const projectionStage = this.findStageInPlan(explainResult, 'PROJECTION_COVERED');
    return projectionStage !== null;
  }

  hasEfficientIndexUsage(explainResult) {
    const selectivity = this.calculateSelectivity(explainResult);
    const indexHitRate = this.calculateIndexHitRate(explainResult);
    return selectivity > 0.1 && indexHitRate > 0.8;
  }

  findStageInPlan(explainResult, stageName) {
    // Recursively search through execution plan for specific stage
    const searchStage = (stage) => {
      if (!stage) return null;

      if (stage.stage === stageName) return stage;

      if (stage.inputStage) {
        const result = searchStage(stage.inputStage);
        if (result) return result;
      }

      if (stage.inputStages) {
        for (const inputStage of stage.inputStages) {
          const result = searchStage(inputStage);
          if (result) return result;
        }
      }

      return null;
    };

    const executionStats = explainResult.executionStats;
    if (executionStats?.executionStages) {
      return searchStage(executionStats.executionStages);
    }

    return null;
  }

  extractIndexesUsed(explainResult) {
    const indexes = new Set();

    const findIndexes = (stage) => {
      if (!stage) return;

      if (stage.indexName) {
        indexes.add(stage.indexName);
      }

      if (stage.inputStage) {
        findIndexes(stage.inputStage);
      }

      if (stage.inputStages) {
        stage.inputStages.forEach(inputStage => findIndexes(inputStage));
      }
    };

    const executionStats = explainResult.executionStats;
    if (executionStats?.executionStages) {
      findIndexes(executionStats.executionStages);
    }

    return Array.from(indexes);
  }

  extractQueryFields(pipeline) {
    // Extract fields used in query conditions
    const fields = {
      equality: [],
      range: [],
      selective: []
    };

    if (Array.isArray(pipeline)) {
      // Aggregation pipeline
      pipeline.forEach(stage => {
        if (stage.$match) {
          this.extractFieldsFromMatch(stage.$match, fields);
        }
      });
    } else if (typeof pipeline === 'object') {
      // Find query
      if (pipeline.find) {
        this.extractFieldsFromMatch(pipeline.find, fields);
      } else {
        this.extractFieldsFromMatch(pipeline, fields);
      }
    }

    return fields;
  }

  extractFieldsFromMatch(matchStage, fields) {
    Object.entries(matchStage).forEach(([field, condition]) => {
      if (field.startsWith('$')) return; // Skip operators

      if (typeof condition === 'object' && condition !== null) {
        const operators = Object.keys(condition);
        if (operators.some(op => ['$gt', '$gte', '$lt', '$lte'].includes(op))) {
          fields.range.push(field);
        } else if (operators.includes('$in')) {
          if (condition.$in.length <= 5) {
            fields.selective.push(field);
          } else {
            fields.equality.push(field);
          }
        } else {
          fields.equality.push(field);
        }
      } else {
        fields.equality.push(field);
      }
    });
  }

  extractSortFields(pipeline) {
    if (Array.isArray(pipeline)) {
      for (const stage of pipeline) {
        if (stage.$sort) {
          return stage.$sort;
        }
      }
    } else if (pipeline.sort) {
      return pipeline.sort;
    }

    return null;
  }

  async recordPerformanceMetrics(collectionName, pipeline, explainResult, analysis) {
    try {
      const metrics = {
        timestamp: new Date(),
        collection: collectionName,
        queryHash: this.generateQueryHash(pipeline),
        pipeline: pipeline,

        execution: {
          timeMs: explainResult.executionStats?.executionTimeMillis || 0,
          docsExamined: explainResult.executionStats?.totalDocsExamined || 0,
          docsReturned: explainResult.executionStats?.totalDocsReturned || 0,
          indexesUsed: this.extractIndexesUsed(explainResult),
          success: explainResult.executionStats?.executionSuccess !== false
        },

        performance: {
          efficiency: this.calculateQueryEfficiency(explainResult),
          indexHitRate: this.calculateIndexHitRate(explainResult),
          selectivity: this.calculateSelectivity(explainResult),
          grade: this.assignPerformanceGrade(explainResult)
        },

        analysis: {
          bottleneckCount: analysis.bottlenecks.length,
          strengthCount: analysis.strengths.length,
          queryType: analysis.queryType,
          riskLevel: this.calculateRiskLevel(analysis.riskFactors)
        }
      };

      await this.collections.analytics.insertOne(metrics);
    } catch (error) {
      console.warn('Failed to record performance metrics:', error.message);
    }
  }

  generateQueryHash(pipeline) {
    // Generate consistent hash for query pattern identification
    const queryString = JSON.stringify(pipeline, Object.keys(pipeline).sort());
    return require('crypto').createHash('md5').update(queryString).digest('hex');
  }

  calculateMemoryUsage(explainResult) {
    // Estimate memory usage from explain plan
    let memoryUsage = 0;

    const sortStage = this.findStageInPlan(explainResult, 'SORT');
    if (sortStage) {
      // Estimate sort memory usage
      memoryUsage += (explainResult.executionStats?.totalDocsExamined || 0) * 0.001; // Rough estimate
    }

    return memoryUsage;
  }

  calculateSortMemoryUsage(explainResult) {
    const stats = explainResult.executionStats;
    if (!stats) return 0;

    // Estimate memory usage for in-memory sort
    const avgDocSize = 1024; // Estimated average document size in bytes
    const docsToSort = stats.totalDocsExamined || 0;

    return (docsToSort * avgDocSize) / (1024 * 1024); // Convert to MB
  }

  async performBatchQueryAnalysis(queries) {
    console.log(`Analyzing batch of ${queries.length} queries...`);

    const results = [];
    const batchMetrics = {
      totalQueries: queries.length,
      analyzedSuccessfully: 0,
      averageExecutionTime: 0,
      averageEfficiency: 0,
      gradeDistribution: { A: 0, B: 0, C: 0, D: 0, F: 0 },
      commonBottlenecks: new Map(),
      recommendationFrequency: new Map()
    };

    for (let i = 0; i < queries.length; i++) {
      const query = queries[i];
      console.log(`Analyzing query ${i + 1}/${queries.length}: ${query.name || 'Unnamed'}`);

      try {
        const analysis = await this.analyzeQueryPerformance(query.collection, query.pipeline, query.options);
        results.push({
          queryIndex: i,
          queryName: query.name || `Query_${i + 1}`,
          analysis: analysis,
          success: true
        });

        // Update batch metrics
        batchMetrics.analyzedSuccessfully++;
        batchMetrics.averageExecutionTime += analysis.execution.totalTimeMs;
        batchMetrics.averageEfficiency += analysis.performance.efficiency;
        batchMetrics.gradeDistribution[analysis.performance.performanceGrade]++;

        // Track common bottlenecks
        analysis.performance.bottlenecks.forEach(bottleneck => {
          const count = batchMetrics.commonBottlenecks.get(bottleneck.type) || 0;
          batchMetrics.commonBottlenecks.set(bottleneck.type, count + 1);
        });

        // Track recommendation frequency
        analysis.optimization.recommendations.forEach(rec => {
          const count = batchMetrics.recommendationFrequency.get(rec.type) || 0;
          batchMetrics.recommendationFrequency.set(rec.type, count + 1);
        });

      } catch (error) {
        console.error(`Query ${i + 1} analysis failed:`, error.message);
        results.push({
          queryIndex: i,
          queryName: query.name || `Query_${i + 1}`,
          error: error.message,
          success: false
        });
      }
    }

    // Calculate final batch metrics
    if (batchMetrics.analyzedSuccessfully > 0) {
      batchMetrics.averageExecutionTime /= batchMetrics.analyzedSuccessfully;
      batchMetrics.averageEfficiency /= batchMetrics.analyzedSuccessfully;
    }

    // Convert Maps to Objects for JSON serialization
    batchMetrics.commonBottlenecks = Object.fromEntries(batchMetrics.commonBottlenecks);
    batchMetrics.recommendationFrequency = Object.fromEntries(batchMetrics.recommendationFrequency);

    console.log(`Batch analysis completed: ${batchMetrics.analyzedSuccessfully}/${batchMetrics.totalQueries} queries analyzed successfully`);
    console.log(`Average execution time: ${batchMetrics.averageExecutionTime.toFixed(2)}ms`);
    console.log(`Average efficiency: ${(batchMetrics.averageEfficiency * 100).toFixed(1)}%`);

    return {
      results: results,
      batchMetrics: batchMetrics,
      summary: {
        totalAnalyzed: batchMetrics.analyzedSuccessfully,
        averagePerformance: batchMetrics.averageEfficiency,
        mostCommonBottleneck: this.getMostCommon(batchMetrics.commonBottlenecks),
        mostCommonRecommendation: this.getMostCommon(batchMetrics.recommendationFrequency),
        performanceDistribution: batchMetrics.gradeDistribution
      }
    };
  }

  getMostCommon(frequency) {
    let maxCount = 0;
    let mostCommon = null;

    Object.entries(frequency).forEach(([key, count]) => {
      if (count > maxCount) {
        maxCount = count;
        mostCommon = key;
      }
    });

    return { type: mostCommon, count: maxCount };
  }

  // Additional helper methods for comprehensive analysis...

  identifyQueryType(explainResult) {
    if (this.findStageInPlan(explainResult, 'GROUP')) return 'aggregation';
    if (this.findStageInPlan(explainResult, 'SORT')) return 'sorted_query';
    if (this.hasLimit(explainResult)) return 'limited_query';
    return 'simple_query';
  }

  analyzeExecutionPattern(explainResult) {
    const pattern = {
      hasIndexScan: this.findStageInPlan(explainResult, 'IXSCAN') !== null,
      hasCollectionScan: this.hasCollectionScan(explainResult),
      hasSort: this.findStageInPlan(explainResult, 'SORT') !== null,
      hasGroup: this.findStageInPlan(explainResult, 'GROUP') !== null,
      hasLimit: this.hasLimit(explainResult)
    };

    return pattern;
  }

  analyzeIndexUsage(explainResult) {
    const indexesUsed = this.extractIndexesUsed(explainResult);
    const hasCollScan = this.hasCollectionScan(explainResult);

    return {
      indexCount: indexesUsed.length,
      indexes: indexesUsed,
      hasCollectionScan: hasCollScan,
      effectiveness: hasCollScan ? 0 : Math.min(1, this.calculateSelectivity(explainResult))
    };
  }

  identifyRiskFactors(explainResult) {
    const risks = [];
    const stats = explainResult.executionStats;

    if (stats?.totalDocsExamined > 100000) {
      risks.push({
        type: 'HIGH_DOCUMENT_EXAMINATION',
        description: 'Query examines very large number of documents',
        impact: 'Scalability concerns, resource intensive'
      });
    }

    if (this.hasCollectionScan(explainResult)) {
      risks.push({
        type: 'COLLECTION_SCAN_SCALING',
        description: 'Collection scan will degrade with data growth',
        impact: 'Linear performance degradation as data grows'
      });
    }

    return risks;
  }

  identifyOptimizationOpportunities(explainResult) {
    const opportunities = [];

    if (this.hasCollectionScan(explainResult)) {
      opportunities.push({
        type: 'INDEX_CREATION',
        description: 'Create appropriate indexes to eliminate collection scans',
        impact: 'Significant performance improvement'
      });
    }

    if (this.hasSortWithoutIndex(explainResult)) {
      opportunities.push({
        type: 'SORT_OPTIMIZATION',
        description: 'Optimize index to support sort operations',
        impact: 'Reduced memory usage and faster sorting'
      });
    }

    return opportunities;
  }

  calculateRiskLevel(riskFactors) {
    if (riskFactors.length === 0) return 'LOW';
    if (riskFactors.some(r => r.type.includes('HIGH') || r.type.includes('CRITICAL'))) return 'HIGH';
    if (riskFactors.length > 2) return 'MEDIUM';
    return 'LOW';
  }
}

// Benefits of MongoDB Query Optimization and Explain Plans:
// - Comprehensive execution plan analysis with detailed performance metrics
// - Automatic bottleneck identification and optimization recommendations
// - Advanced index usage analysis and index suggestion algorithms
// - Real-time query performance monitoring and historical trending
// - Intelligent query alternative generation and comparative analysis
// - Integration with aggregation pipeline optimization techniques
// - Detailed memory usage analysis and resource consumption tracking
// - Batch query analysis capabilities for application-wide performance review
// - Automated performance grading and risk assessment
// - Production-ready performance monitoring and alerting integration

module.exports = {
  MongoQueryOptimizer
};

Understanding MongoDB Query Optimization Architecture

Advanced Query Analysis Techniques and Performance Tuning

Implement sophisticated query analysis patterns for production optimization:

// Advanced query optimization patterns and performance monitoring
class AdvancedQueryAnalyzer {
  constructor(db) {
    this.db = db;
    this.performanceHistory = new Map();
    this.optimizationRules = new Map();
    this.alertThresholds = {
      executionTimeMs: 1000,
      docsExaminedRatio: 10,
      indexHitRate: 0.8
    };
  }

  async implementRealTimePerformanceMonitoring(collections) {
    console.log('Setting up real-time query performance monitoring...');

    // Enable database profiling for detailed query analysis
    await this.db.runCommand({
      profile: 2, // Profile all operations
      slowms: 100, // Log operations slower than 100ms
      sampleRate: 0.1 // Sample 10% of operations
    });

    // Create performance monitoring aggregation pipeline
    const monitoringPipeline = [
      {
        $match: {
          ts: { $gte: new Date(Date.now() - 60000) }, // Last minute
          ns: { $in: collections.map(col => `${this.db.databaseName}.${col}`) },
          command: { $exists: true }
        }
      },
      {
        $addFields: {
          queryType: {
            $switch: {
              branches: [
                { case: { $ne: ['$command.find', null] }, then: 'find' },
                { case: { $ne: ['$command.aggregate', null] }, then: 'aggregate' },
                { case: { $ne: ['$command.update', null] }, then: 'update' },
                { case: { $ne: ['$command.delete', null] }, then: 'delete' }
              ],
              default: 'other'
            }
          },

          // Extract query shape for pattern analysis
          queryShape: {
            $switch: {
              branches: [
                {
                  case: { $ne: ['$command.find', null] },
                  then: { $objectToArray: { $ifNull: ['$command.filter', {}] } }
                },
                {
                  case: { $ne: ['$command.aggregate', null] },
                  then: { $arrayElemAt: ['$command.pipeline', 0] }
                }
              ],
              default: {}
            }
          },

          // Performance metrics calculation
          efficiency: {
            $cond: {
              if: { $gt: ['$docsExamined', 0] },
              then: { $divide: ['$nreturned', '$docsExamined'] },
              else: 1
            }
          },

          // Index usage assessment
          indexUsed: {
            $cond: {
              if: { $ne: ['$planSummary', null] },
              then: { $not: { $regexMatch: { input: '$planSummary', regex: 'COLLSCAN' } } },
              else: false
            }
          }
        }
      },
      {
        $group: {
          _id: {
            collection: { $arrayElemAt: [{ $split: ['$ns', '.'] }, 1] },
            queryType: '$queryType',
            queryShape: '$queryShape'
          },

          // Aggregated performance metrics
          avgExecutionTime: { $avg: '$millis' },
          maxExecutionTime: { $max: '$millis' },
          totalQueries: { $sum: 1 },
          avgEfficiency: { $avg: '$efficiency' },
          avgDocsExamined: { $avg: '$docsExamined' },
          avgDocsReturned: { $avg: '$nreturned' },
          indexUsageRate: { $avg: { $cond: ['$indexUsed', 1, 0] } },

          // Query examples for further analysis
          sampleQueries: { $push: { command: '$command', millis: '$millis' } }
        }
      },
      {
        $match: {
          $or: [
            { avgExecutionTime: { $gt: this.alertThresholds.executionTimeMs } },
            { avgEfficiency: { $lt: 0.1 } },
            { indexUsageRate: { $lt: this.alertThresholds.indexHitRate } }
          ]
        }
      },
      {
        $sort: { avgExecutionTime: -1 }
      }
    ];

    try {
      const performanceIssues = await this.db.collection('system.profile')
        .aggregate(monitoringPipeline).toArray();

      // Process identified performance issues
      for (const issue of performanceIssues) {
        await this.processPerformanceIssue(issue);
      }

      console.log(`Performance monitoring identified ${performanceIssues.length} potential issues`);
      return performanceIssues;

    } catch (error) {
      console.error('Performance monitoring failed:', error);
      return [];
    }
  }

  async processPerformanceIssue(issue) {
    const issueSignature = this.generateIssueSignature(issue);

    // Check if this issue has been seen before
    if (this.performanceHistory.has(issueSignature)) {
      const history = this.performanceHistory.get(issueSignature);
      history.occurrences++;
      history.lastSeen = new Date();

      // Escalate if recurring issue
      if (history.occurrences > 5) {
        await this.escalatePerformanceIssue(issue, history);
      }
    } else {
      // New issue, add to tracking
      this.performanceHistory.set(issueSignature, {
        firstSeen: new Date(),
        lastSeen: new Date(),
        occurrences: 1,
        issue: issue
      });
    }

    // Generate optimization recommendations
    const recommendations = await this.generateRealtimeRecommendations(issue);

    // Log performance alert
    await this.logPerformanceAlert({
      timestamp: new Date(),
      collection: issue._id.collection,
      queryType: issue._id.queryType,
      severity: this.calculateSeverity(issue),
      metrics: {
        avgExecutionTime: issue.avgExecutionTime,
        avgEfficiency: issue.avgEfficiency,
        indexUsageRate: issue.indexUsageRate,
        totalQueries: issue.totalQueries
      },
      recommendations: recommendations,
      issueSignature: issueSignature
    });
  }

  async generateRealtimeRecommendations(issue) {
    const recommendations = [];

    // Low index usage rate
    if (issue.indexUsageRate < this.alertThresholds.indexHitRate) {
      recommendations.push({
        type: 'INDEX_OPTIMIZATION',
        priority: 'HIGH',
        description: `Collection ${issue._id.collection} has low index usage rate (${(issue.indexUsageRate * 100).toFixed(1)}%)`,
        action: 'Analyze query patterns and create appropriate indexes',
        queryType: issue._id.queryType
      });
    }

    // High execution time
    if (issue.avgExecutionTime > this.alertThresholds.executionTimeMs) {
      recommendations.push({
        type: 'PERFORMANCE_OPTIMIZATION',
        priority: 'HIGH',
        description: `Queries on ${issue._id.collection} averaging ${issue.avgExecutionTime.toFixed(2)}ms execution time`,
        action: 'Review query structure and index strategy',
        queryType: issue._id.queryType
      });
    }

    // Poor efficiency
    if (issue.avgEfficiency < 0.1) {
      recommendations.push({
        type: 'SELECTIVITY_IMPROVEMENT',
        priority: 'MEDIUM',
        description: `Poor query selectivity detected (${(issue.avgEfficiency * 100).toFixed(1)}% efficiency)`,
        action: 'Implement more selective query filters or partial indexes',
        queryType: issue._id.queryType
      });
    }

    return recommendations;
  }

  async performHistoricalPerformanceAnalysis(timeRange = '7d') {
    console.log(`Performing historical performance analysis for ${timeRange}...`);

    const timeRangeMs = this.parseTimeRange(timeRange);
    const startDate = new Date(Date.now() - timeRangeMs);

    const historicalAnalysis = await this.db.collection('system.profile').aggregate([
      {
        $match: {
          ts: { $gte: startDate },
          command: { $exists: true },
          millis: { $exists: true }
        }
      },
      {
        $addFields: {
          hour: { $dateToString: { format: '%Y-%m-%d-%H', date: '$ts' } },
          collection: { $arrayElemAt: [{ $split: ['$ns', '.'] }, 1] },
          queryType: {
            $switch: {
              branches: [
                { case: { $ne: ['$command.find', null] }, then: 'find' },
                { case: { $ne: ['$command.aggregate', null] }, then: 'aggregate' },
                { case: { $ne: ['$command.update', null] }, then: 'update' }
              ],
              default: 'other'
            }
          }
        }
      },
      {
        $group: {
          _id: {
            hour: '$hour',
            collection: '$collection',
            queryType: '$queryType'
          },

          // Time-based metrics
          queryCount: { $sum: 1 },
          avgLatency: { $avg: '$millis' },
          maxLatency: { $max: '$millis' },
          p95Latency: { 
            $percentile: { 
              input: '$millis', 
              p: [0.95], 
              method: 'approximate' 
            }
          },

          // Efficiency metrics
          totalDocsExamined: { $sum: '$docsExamined' },
          totalDocsReturned: { $sum: '$nreturned' },
          avgEfficiency: {
            $avg: {
              $cond: {
                if: { $gt: ['$docsExamined', 0] },
                then: { $divide: ['$nreturned', '$docsExamined'] },
                else: 1
              }
            }
          },

          // Index usage tracking
          collectionScans: {
            $sum: {
              $cond: [
                { $regexMatch: { input: { $ifNull: ['$planSummary', ''] }, regex: 'COLLSCAN' } },
                1,
                0
              ]
            }
          }
        }
      },
      {
        $addFields: {
          indexUsageRate: {
            $subtract: [1, { $divide: ['$collectionScans', '$queryCount'] }]
          },

          // Performance trend calculation
          performanceScore: {
            $add: [
              { $multiply: [{ $min: [1, { $divide: [1000, '$avgLatency'] }] }, 0.4] },
              { $multiply: ['$avgEfficiency', 0.3] },
              { $multiply: ['$indexUsageRate', 0.3] }
            ]
          }
        }
      },
      {
        $sort: { '_id.hour': 1, performanceScore: 1 }
      }
    ]).toArray();

    // Analyze trends and patterns
    const trendAnalysis = this.analyzePerformanceTrends(historicalAnalysis);
    const recommendations = this.generateHistoricalRecommendations(trendAnalysis);

    return {
      timeRange: timeRange,
      analysis: historicalAnalysis,
      trends: trendAnalysis,
      recommendations: recommendations,
      summary: {
        totalHours: new Set(historicalAnalysis.map(h => h._id.hour)).size,
        collectionsAnalyzed: new Set(historicalAnalysis.map(h => h._id.collection)).size,
        avgPerformanceScore: historicalAnalysis.reduce((sum, h) => sum + h.performanceScore, 0) / historicalAnalysis.length,
        worstPerformingHour: historicalAnalysis[0],
        bestPerformingHour: historicalAnalysis[historicalAnalysis.length - 1]
      }
    };
  }

  analyzePerformanceTrends(historicalData) {
    const trends = {
      latencyTrend: this.calculateTrend(historicalData, 'avgLatency'),
      throughputTrend: this.calculateTrend(historicalData, 'queryCount'),
      efficiencyTrend: this.calculateTrend(historicalData, 'avgEfficiency'),
      indexUsageTrend: this.calculateTrend(historicalData, 'indexUsageRate'),

      // Peak usage analysis
      peakHours: this.identifyPeakHours(historicalData),

      // Performance degradation detection
      degradationPeriods: this.identifyDegradationPeriods(historicalData),

      // Collection-specific trends
      collectionTrends: this.analyzeCollectionTrends(historicalData)
    };

    return trends;
  }

  calculateTrend(data, metric) {
    if (data.length < 2) return { direction: 'stable', magnitude: 0 };

    const values = data.map(d => d[metric]).filter(v => v != null);
    const n = values.length;

    if (n < 2) return { direction: 'stable', magnitude: 0 };

    // Simple linear regression for trend calculation
    const xSum = (n * (n + 1)) / 2;
    const ySum = values.reduce((sum, val) => sum + val, 0);
    const xySum = values.reduce((sum, val, i) => sum + val * (i + 1), 0);
    const x2Sum = (n * (n + 1) * (2 * n + 1)) / 6;

    const slope = (n * xySum - xSum * ySum) / (n * x2Sum - xSum * xSum);
    const magnitude = Math.abs(slope);

    let direction = 'stable';
    if (slope > magnitude * 0.1) direction = 'improving';
    else if (slope < -magnitude * 0.1) direction = 'degrading';

    return { direction, magnitude, slope };
  }

  async implementAutomatedOptimization(collectionName, optimizationRules) {
    console.log(`Implementing automated optimization for ${collectionName}...`);

    const collection = this.db.collection(collectionName);
    const optimizationResults = [];

    for (const rule of optimizationRules) {
      try {
        switch (rule.type) {
          case 'AUTO_INDEX_CREATION':
            const indexResult = await this.createOptimizedIndex(collection, rule);
            optimizationResults.push(indexResult);
            break;

          case 'QUERY_REWRITE':
            const rewriteResult = await this.implementQueryRewrite(collection, rule);
            optimizationResults.push(rewriteResult);
            break;

          case 'AGGREGATION_OPTIMIZATION':
            const aggResult = await this.optimizeAggregationPipeline(collection, rule);
            optimizationResults.push(aggResult);
            break;

          default:
            console.warn(`Unknown optimization rule type: ${rule.type}`);
        }
      } catch (error) {
        console.error(`Optimization rule ${rule.type} failed:`, error);
        optimizationResults.push({
          rule: rule.type,
          success: false,
          error: error.message
        });
      }
    }

    // Validate optimization effectiveness
    const validationResults = await this.validateOptimizations(collection, optimizationResults);

    return {
      collection: collectionName,
      optimizationsApplied: optimizationResults,
      validation: validationResults,
      summary: {
        totalRules: optimizationRules.length,
        successful: optimizationResults.filter(r => r.success).length,
        failed: optimizationResults.filter(r => !r.success).length
      }
    };
  }

  async createOptimizedIndex(collection, rule) {
    console.log(`Creating optimized index: ${rule.indexName}`);

    try {
      const indexSpec = rule.indexSpec;
      const indexOptions = rule.indexOptions || {};

      // Add background: true for production safety
      indexOptions.background = true;

      await collection.createIndex(indexSpec, {
        name: rule.indexName,
        ...indexOptions
      });

      // Test index effectiveness
      const testResult = await this.testIndexEffectiveness(collection, rule);

      return {
        rule: 'AUTO_INDEX_CREATION',
        indexName: rule.indexName,
        indexSpec: indexSpec,
        success: true,
        effectiveness: testResult,
        message: `Index ${rule.indexName} created successfully`
      };

    } catch (error) {
      return {
        rule: 'AUTO_INDEX_CREATION',
        indexName: rule.indexName,
        success: false,
        error: error.message
      };
    }
  }

  async testIndexEffectiveness(collection, rule) {
    if (!rule.testQuery) return { tested: false };

    try {
      // Execute test query with explain
      const explainResult = await collection.find(rule.testQuery).explain('executionStats');

      const effectiveness = {
        tested: true,
        indexUsed: !this.hasCollectionScan(explainResult),
        executionTimeMs: explainResult.executionStats?.executionTimeMillis || 0,
        docsExamined: explainResult.executionStats?.totalDocsExamined || 0,
        docsReturned: explainResult.executionStats?.totalDocsReturned || 0,
        efficiency: this.calculateQueryEfficiency(explainResult)
      };

      return effectiveness;

    } catch (error) {
      return {
        tested: false,
        error: error.message
      };
    }
  }

  // Additional helper methods...

  generateIssueSignature(issue) {
    const key = JSON.stringify({
      collection: issue._id.collection,
      queryType: issue._id.queryType,
      queryShape: issue._id.queryShape
    });
    return require('crypto').createHash('md5').update(key).digest('hex');
  }

  calculateSeverity(issue) {
    let score = 0;

    if (issue.avgExecutionTime > 2000) score += 3;
    else if (issue.avgExecutionTime > 1000) score += 2;
    else if (issue.avgExecutionTime > 500) score += 1;

    if (issue.avgEfficiency < 0.05) score += 3;
    else if (issue.avgEfficiency < 0.1) score += 2;
    else if (issue.avgEfficiency < 0.2) score += 1;

    if (issue.indexUsageRate < 0.5) score += 2;
    else if (issue.indexUsageRate < 0.8) score += 1;

    if (score >= 6) return 'CRITICAL';
    else if (score >= 4) return 'HIGH';
    else if (score >= 2) return 'MEDIUM';
    else return 'LOW';
  }

  parseTimeRange(timeRange) {
    const units = {
      'd': 24 * 60 * 60 * 1000,
      'h': 60 * 60 * 1000,
      'm': 60 * 1000
    };

    const match = timeRange.match(/(\d+)([dhm])/);
    if (!match) return 7 * 24 * 60 * 60 * 1000; // Default 7 days

    const [, amount, unit] = match;
    return parseInt(amount) * units[unit];
  }

  async logPerformanceAlert(alert) {
    try {
      await this.db.collection('performance_alerts').insertOne(alert);
    } catch (error) {
      console.warn('Failed to log performance alert:', error.message);
    }
  }
}

SQL-Style Query Analysis with QueryLeaf

QueryLeaf provides familiar SQL syntax for MongoDB query optimization and explain plan analysis:

-- QueryLeaf query optimization with SQL-familiar EXPLAIN syntax

-- Basic query explain with performance analysis
EXPLAIN (ANALYZE true, BUFFERS true, TIMING true)
SELECT 
  user_id,
  email,
  first_name,
  last_name,
  status,
  created_at
FROM users 
WHERE status = 'active' 
  AND country IN ('US', 'CA', 'UK')
  AND created_at >= CURRENT_DATE - INTERVAL '1 year'
ORDER BY created_at DESC
LIMIT 100;

-- Advanced aggregation explain with optimization recommendations  
EXPLAIN (ANALYZE true, COSTS true, VERBOSE true, FORMAT JSON)
WITH user_activity_summary AS (
  SELECT 
    u.user_id,
    u.email,
    u.first_name,
    u.last_name,
    u.country,
    u.status,
    COUNT(o.order_id) as order_count,
    SUM(o.total_amount) as total_spent,
    AVG(o.total_amount) as avg_order_value,
    MAX(o.created_at) as last_order_date,

    -- Customer value segmentation
    CASE 
      WHEN SUM(o.total_amount) > 1000 THEN 'high_value'
      WHEN SUM(o.total_amount) > 100 THEN 'medium_value'
      ELSE 'low_value'
    END as value_segment,

    -- Activity recency scoring
    CASE 
      WHEN MAX(o.created_at) >= CURRENT_DATE - INTERVAL '30 days' THEN 'recent'
      WHEN MAX(o.created_at) >= CURRENT_DATE - INTERVAL '90 days' THEN 'moderate' 
      WHEN MAX(o.created_at) >= CURRENT_DATE - INTERVAL '1 year' THEN 'old'
      ELSE 'inactive'
    END as activity_segment

  FROM users u
  LEFT JOIN orders o ON u.user_id = o.user_id 
  WHERE u.status = 'active'
    AND u.country IN ('US', 'CA', 'UK', 'AU', 'DE')
    AND u.created_at >= CURRENT_DATE - INTERVAL '2 years'
    AND (o.status = 'completed' OR o.status IS NULL)
  GROUP BY u.user_id, u.email, u.first_name, u.last_name, u.country, u.status
  HAVING COUNT(o.order_id) > 0 OR u.created_at >= CURRENT_DATE - INTERVAL '6 months'
),

customer_insights AS (
  SELECT 
    country,
    value_segment,
    activity_segment,
    COUNT(*) as customer_count,
    AVG(total_spent) as avg_customer_value,
    SUM(order_count) as total_orders,

    -- Geographic performance metrics
    AVG(order_count) as avg_orders_per_customer,
    PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY total_spent) as median_customer_value,
    STDDEV(total_spent) as customer_value_stddev,

    -- Customer concentration analysis
    COUNT(*) / SUM(COUNT(*)) OVER (PARTITION BY country) as segment_concentration,

    -- Activity trend indicators
    COUNT(*) FILTER (WHERE activity_segment = 'recent') as recent_active_customers,
    COUNT(*) FILTER (WHERE activity_segment IN ('moderate', 'old')) as declining_customers

  FROM user_activity_summary
  GROUP BY country, value_segment, activity_segment
)

SELECT 
  country,
  value_segment,
  activity_segment,
  customer_count,
  ROUND(avg_customer_value::numeric, 2) as avg_customer_ltv,
  total_orders,
  ROUND(avg_orders_per_customer::numeric, 1) as avg_orders_per_customer,
  ROUND(median_customer_value::numeric, 2) as median_ltv,
  ROUND(segment_concentration::numeric, 4) as market_concentration,

  -- Performance indicators
  CASE 
    WHEN recent_active_customers > declining_customers THEN 'growing'
    WHEN recent_active_customers < declining_customers * 0.5 THEN 'declining'
    ELSE 'stable'
  END as segment_trend,

  -- Business intelligence insights
  CASE
    WHEN value_segment = 'high_value' AND activity_segment = 'recent' THEN 'premium_active'
    WHEN value_segment = 'high_value' AND activity_segment != 'recent' THEN 'at_risk_premium'
    WHEN value_segment != 'low_value' AND activity_segment = 'recent' THEN 'growth_opportunity'
    WHEN activity_segment = 'inactive' THEN 'reactivation_target'
    ELSE 'standard_segment'
  END as strategic_priority,

  -- Ranking within country
  ROW_NUMBER() OVER (
    PARTITION BY country 
    ORDER BY avg_customer_value DESC, customer_count DESC
  ) as country_segment_rank

FROM customer_insights
WHERE customer_count >= 10  -- Filter small segments
ORDER BY country, avg_customer_value DESC, customer_count DESC;

-- QueryLeaf EXPLAIN output with optimization insights:
-- {
--   "queryType": "aggregation",
--   "executionTimeMillis": 245,
--   "totalDocsExamined": 45678,
--   "totalDocsReturned": 1245,
--   "efficiency": 0.027,
--   "indexUsage": {
--     "indexes": ["users_status_country_idx", "orders_user_status_idx"],
--     "effectiveness": 0.78,
--     "missingIndexes": ["users_created_at_idx", "orders_completed_date_idx"]
--   },
--   "stages": [
--     {
--       "stage": "$match",
--       "inputStage": "IXSCAN",
--       "indexName": "users_status_country_idx",
--       "keysExamined": 12456,
--       "docsExamined": 8901,
--       "executionTimeMillis": 45,
--       "optimization": "GOOD - Using compound index efficiently"
--     },
--     {
--       "stage": "$lookup", 
--       "inputStage": "IXSCAN",
--       "indexName": "orders_user_status_idx",
--       "executionTimeMillis": 156,
--       "optimization": "NEEDS_IMPROVEMENT - Consider creating index on (user_id, status, created_at)"
--     },
--     {
--       "stage": "$group",
--       "executionTimeMillis": 34,
--       "memoryUsageMB": 12.3,
--       "spilledToDisk": false,
--       "optimization": "GOOD - Group operation within memory limits"
--     },
--     {
--       "stage": "$sort",
--       "executionTimeMillis": 10,
--       "memoryUsageMB": 2.1,
--       "optimization": "EXCELLENT - Sort using index order"
--     }
--   ],
--   "recommendations": [
--     {
--       "type": "CREATE_INDEX",
--       "priority": "HIGH",
--       "description": "Create compound index to improve JOIN performance",
--       "suggestedIndex": "CREATE INDEX orders_user_status_date_idx ON orders (user_id, status, created_at DESC)",
--       "estimatedImprovement": "60-80% reduction in lookup time"
--     },
--     {
--       "type": "QUERY_RESTRUCTURE",
--       "priority": "MEDIUM", 
--       "description": "Consider splitting complex aggregation into smaller stages",
--       "estimatedImprovement": "20-40% better resource utilization"
--     }
--   ],
--   "performanceGrade": "C+",
--   "bottlenecks": [
--     {
--       "stage": "$lookup",
--       "issue": "Examining too many documents in joined collection",
--       "impact": "63% of total execution time"
--     }
--   ]
-- }

-- Performance monitoring and optimization tracking
WITH query_performance_analysis AS (
  SELECT 
    DATE_TRUNC('hour', execution_timestamp) as hour_bucket,
    collection_name,
    query_type,

    -- Performance metrics
    COUNT(*) as query_count,
    AVG(execution_time_ms) as avg_execution_time,
    PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY execution_time_ms) as p95_execution_time,
    MAX(execution_time_ms) as max_execution_time,

    -- Resource utilization
    AVG(docs_examined) as avg_docs_examined,
    AVG(docs_returned) as avg_docs_returned,
    AVG(docs_examined::float / GREATEST(docs_returned, 1)) as avg_scan_ratio,

    -- Index effectiveness
    COUNT(*) FILTER (WHERE index_used = true) as queries_with_index,
    AVG(CASE WHEN index_used THEN 1.0 ELSE 0.0 END) as index_hit_rate,
    STRING_AGG(DISTINCT index_name, ', ') as indexes_used,

    -- Error tracking
    COUNT(*) FILTER (WHERE execution_success = false) as failed_queries,
    STRING_AGG(DISTINCT error_type, '; ') FILTER (WHERE error_type IS NOT NULL) as error_types,

    -- Memory and I/O metrics
    AVG(memory_usage_mb) as avg_memory_usage,
    MAX(memory_usage_mb) as peak_memory_usage,
    COUNT(*) FILTER (WHERE spilled_to_disk = true) as queries_spilled_to_disk

  FROM query_execution_log
  WHERE execution_timestamp >= CURRENT_TIMESTAMP - INTERVAL '24 hours'
    AND collection_name IN ('users', 'orders', 'products', 'analytics')
  GROUP BY DATE_TRUNC('hour', execution_timestamp), collection_name, query_type
),

performance_scoring AS (
  SELECT 
    *,
    -- Performance score calculation (0-100)
    LEAST(100, GREATEST(0,
      -- Execution time score (40% weight)
      (CASE 
        WHEN avg_execution_time <= 50 THEN 40
        WHEN avg_execution_time <= 100 THEN 30
        WHEN avg_execution_time <= 250 THEN 20
        WHEN avg_execution_time <= 500 THEN 10
        ELSE 0
      END) +

      -- Index usage score (35% weight)
      (index_hit_rate * 35) +

      -- Scan efficiency score (25% weight)  
      (CASE
        WHEN avg_scan_ratio <= 1.1 THEN 25
        WHEN avg_scan_ratio <= 2.0 THEN 20
        WHEN avg_scan_ratio <= 5.0 THEN 15
        WHEN avg_scan_ratio <= 10.0 THEN 10
        ELSE 0
      END)
    )) as performance_score,

    -- Performance grade assignment
    CASE 
      WHEN avg_execution_time <= 50 AND index_hit_rate >= 0.9 AND avg_scan_ratio <= 1.5 THEN 'A'
      WHEN avg_execution_time <= 100 AND index_hit_rate >= 0.8 AND avg_scan_ratio <= 3.0 THEN 'B'
      WHEN avg_execution_time <= 250 AND index_hit_rate >= 0.6 AND avg_scan_ratio <= 10.0 THEN 'C'
      WHEN avg_execution_time <= 500 AND index_hit_rate >= 0.4 THEN 'D'
      ELSE 'F'
    END as performance_grade,

    -- Trend analysis (comparing with previous period)
    LAG(avg_execution_time) OVER (
      PARTITION BY collection_name, query_type 
      ORDER BY hour_bucket
    ) as prev_avg_execution_time,

    LAG(index_hit_rate) OVER (
      PARTITION BY collection_name, query_type
      ORDER BY hour_bucket
    ) as prev_index_hit_rate,

    LAG(performance_score) OVER (
      PARTITION BY collection_name, query_type
      ORDER BY hour_bucket  
    ) as prev_performance_score

  FROM query_performance_analysis
),

optimization_recommendations AS (
  SELECT 
    collection_name,
    query_type,
    hour_bucket,
    performance_grade,
    performance_score,

    -- Performance trend indicators
    CASE 
      WHEN prev_performance_score IS NOT NULL THEN
        CASE 
          WHEN performance_score > prev_performance_score + 10 THEN 'IMPROVING'
          WHEN performance_score < prev_performance_score - 10 THEN 'DEGRADING'
          ELSE 'STABLE'
        END
      ELSE 'NEW'
    END as performance_trend,

    -- Specific optimization recommendations
    ARRAY_REMOVE(ARRAY[
      CASE 
        WHEN index_hit_rate < 0.8 THEN 'CREATE_MISSING_INDEXES'
        ELSE NULL
      END,
      CASE
        WHEN avg_scan_ratio > 10 THEN 'IMPROVE_QUERY_SELECTIVITY' 
        ELSE NULL
      END,
      CASE
        WHEN avg_execution_time > 500 THEN 'OPTIMIZE_QUERY_STRUCTURE'
        ELSE NULL
      END,
      CASE
        WHEN failed_queries > query_count * 0.05 THEN 'INVESTIGATE_QUERY_FAILURES'
        ELSE NULL
      END,
      CASE
        WHEN queries_spilled_to_disk > 0 THEN 'REDUCE_MEMORY_USAGE'
        ELSE NULL
      END
    ], NULL) as optimization_actions,

    -- Priority calculation
    CASE
      WHEN performance_grade IN ('D', 'F') AND query_count > 100 THEN 'CRITICAL'
      WHEN performance_grade = 'C' AND query_count > 500 THEN 'HIGH'
      WHEN performance_grade IN ('C', 'D') AND query_count > 50 THEN 'MEDIUM'
      ELSE 'LOW'
    END as optimization_priority,

    -- Detailed metrics for analysis
    query_count,
    avg_execution_time,
    p95_execution_time,
    index_hit_rate,
    avg_scan_ratio,
    failed_queries,
    indexes_used,
    error_types

  FROM performance_scoring
  WHERE query_count >= 5  -- Filter low-volume queries
)

SELECT 
  collection_name,
  query_type,
  performance_grade,
  ROUND(performance_score::numeric, 1) as performance_score,
  performance_trend,
  optimization_priority,

  -- Key performance indicators
  query_count as hourly_query_count,
  ROUND(avg_execution_time::numeric, 2) as avg_latency_ms,
  ROUND(p95_execution_time::numeric, 2) as p95_latency_ms,
  ROUND((index_hit_rate * 100)::numeric, 1) as index_hit_rate_pct,
  ROUND(avg_scan_ratio::numeric, 2) as avg_selectivity_ratio,

  -- Optimization guidance  
  CASE
    WHEN ARRAY_LENGTH(optimization_actions, 1) > 0 THEN
      'Recommended actions: ' || ARRAY_TO_STRING(optimization_actions, ', ')
    ELSE 'Performance within acceptable parameters'
  END as optimization_guidance,

  -- Resource impact assessment
  CASE
    WHEN query_count > 1000 AND performance_grade IN ('D', 'F') THEN 'HIGH_IMPACT'
    WHEN query_count > 500 AND performance_grade = 'C' THEN 'MEDIUM_IMPACT'
    ELSE 'LOW_IMPACT'
  END as resource_impact,

  -- Technical details
  indexes_used,
  error_types,
  hour_bucket as analysis_hour

FROM optimization_recommendations
WHERE optimization_priority IN ('CRITICAL', 'HIGH', 'MEDIUM')
   OR performance_trend = 'DEGRADING'
ORDER BY 
  CASE optimization_priority
    WHEN 'CRITICAL' THEN 1
    WHEN 'HIGH' THEN 2  
    WHEN 'MEDIUM' THEN 3
    ELSE 4
  END,
  performance_score ASC,
  query_count DESC;

-- Real-time query optimization with automated recommendations
CREATE OR REPLACE VIEW query_optimization_dashboard AS
WITH current_performance AS (
  SELECT 
    collection_name,
    query_hash,
    query_pattern,

    -- Recent performance metrics (last hour)
    COUNT(*) as recent_executions,
    AVG(execution_time_ms) as current_avg_time,
    PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY execution_time_ms) as current_p95_time,
    AVG(docs_examined::float / GREATEST(docs_returned, 1)) as current_scan_ratio,

    -- Index usage analysis
    BOOL_AND(index_used) as all_queries_use_index,
    COUNT(DISTINCT index_name) as unique_indexes_used,
    MODE() WITHIN GROUP (ORDER BY index_name) as most_common_index,

    -- Error rate tracking
    AVG(CASE WHEN execution_success THEN 1.0 ELSE 0.0 END) as success_rate

  FROM query_execution_log
  WHERE execution_timestamp >= CURRENT_TIMESTAMP - INTERVAL '1 hour'
  GROUP BY collection_name, query_hash, query_pattern
  HAVING COUNT(*) >= 5  -- Minimum threshold for analysis
),

historical_baseline AS (
  SELECT 
    collection_name,
    query_hash,

    -- Historical baseline metrics (previous 24 hours, excluding last hour)
    AVG(execution_time_ms) as baseline_avg_time,
    PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY execution_time_ms) as baseline_p95_time,
    AVG(docs_examined::float / GREATEST(docs_returned, 1)) as baseline_scan_ratio,
    AVG(CASE WHEN execution_success THEN 1.0 ELSE 0.0 END) as baseline_success_rate

  FROM query_execution_log  
  WHERE execution_timestamp >= CURRENT_TIMESTAMP - INTERVAL '25 hours'
    AND execution_timestamp < CURRENT_TIMESTAMP - INTERVAL '1 hour'
  GROUP BY collection_name, query_hash
  HAVING COUNT(*) >= 20  -- Sufficient historical data
)

SELECT 
  cp.collection_name,
  cp.query_pattern,
  cp.recent_executions,

  -- Performance comparison
  ROUND(cp.current_avg_time::numeric, 2) as current_avg_latency_ms,
  ROUND(hb.baseline_avg_time::numeric, 2) as baseline_avg_latency_ms,
  ROUND(((cp.current_avg_time - hb.baseline_avg_time) / hb.baseline_avg_time * 100)::numeric, 1) as latency_change_pct,

  -- Performance status classification
  CASE 
    WHEN cp.current_avg_time > hb.baseline_avg_time * 1.5 THEN 'DEGRADED'
    WHEN cp.current_avg_time > hb.baseline_avg_time * 1.2 THEN 'SLOWER'
    WHEN cp.current_avg_time < hb.baseline_avg_time * 0.8 THEN 'IMPROVED'
    ELSE 'STABLE'
  END as performance_status,

  -- Index utilization
  cp.all_queries_use_index,
  cp.unique_indexes_used,
  cp.most_common_index,

  -- Scan efficiency
  ROUND(cp.current_scan_ratio::numeric, 2) as current_scan_ratio,
  ROUND(hb.baseline_scan_ratio::numeric, 2) as baseline_scan_ratio,

  -- Reliability metrics
  ROUND((cp.success_rate * 100)::numeric, 2) as success_rate_pct,
  ROUND((hb.baseline_success_rate * 100)::numeric, 2) as baseline_success_rate_pct,

  -- Automated optimization recommendations
  CASE
    WHEN NOT cp.all_queries_use_index THEN 'CRITICAL: Create missing indexes for consistent performance'
    WHEN cp.current_avg_time > hb.baseline_avg_time * 2 THEN 'HIGH: Investigate severe performance regression'
    WHEN cp.current_scan_ratio > hb.baseline_scan_ratio * 2 THEN 'MEDIUM: Review query selectivity and filters'
    WHEN cp.success_rate < 0.95 THEN 'MEDIUM: Address query reliability issues'
    WHEN cp.current_avg_time > hb.baseline_avg_time * 1.2 THEN 'LOW: Monitor for continued degradation'
    ELSE 'No immediate action required'
  END as recommended_action,

  -- Alert priority
  CASE 
    WHEN NOT cp.all_queries_use_index OR cp.current_avg_time > hb.baseline_avg_time * 2 THEN 'ALERT'
    WHEN cp.current_avg_time > hb.baseline_avg_time * 1.5 OR cp.success_rate < 0.9 THEN 'WARNING'
    ELSE 'INFO'
  END as alert_level

FROM current_performance cp
LEFT JOIN historical_baseline hb ON cp.collection_name = hb.collection_name 
                                 AND cp.query_hash = hb.query_hash
ORDER BY 
  CASE 
    WHEN NOT cp.all_queries_use_index OR cp.current_avg_time > COALESCE(hb.baseline_avg_time * 2, 1000) THEN 1
    WHEN cp.current_avg_time > COALESCE(hb.baseline_avg_time * 1.5, 500) THEN 2
    ELSE 3
  END,
  cp.recent_executions DESC;

-- QueryLeaf provides comprehensive query optimization capabilities:
-- 1. SQL-familiar EXPLAIN syntax with detailed execution plan analysis
-- 2. Advanced performance monitoring with historical trend analysis
-- 3. Automated index recommendations based on query patterns
-- 4. Real-time performance alerts and degradation detection
-- 5. Comprehensive bottleneck identification and optimization guidance
-- 6. Resource usage tracking and capacity planning insights
-- 7. Query efficiency scoring and performance grading systems
-- 8. Integration with MongoDB's native explain plan functionality
-- 9. Batch query analysis for application-wide performance review
-- 10. Production-ready monitoring dashboards and optimization workflows

Best Practices for Query Optimization Implementation

Query Analysis Strategy

Essential principles for effective MongoDB query optimization:

  1. Regular Monitoring: Implement continuous query performance monitoring and alerting
  2. Index Strategy: Design indexes based on actual query patterns and performance data
  3. Explain Plan Analysis: Use comprehensive explain plan analysis to identify bottlenecks
  4. Historical Tracking: Maintain historical performance data to identify trends and regressions
  5. Automated Optimization: Implement automated optimization recommendations and validation
  6. Production Safety: Test all optimizations thoroughly before applying to production systems

Performance Tuning Workflow

Optimize MongoDB queries systematically:

  1. Performance Baseline: Establish performance baselines and targets for all critical queries
  2. Bottleneck Identification: Use explain plans to identify specific performance bottlenecks
  3. Optimization Implementation: Apply optimizations following proven patterns and best practices
  4. Validation Testing: Validate optimization effectiveness with comprehensive testing
  5. Monitoring Setup: Implement ongoing monitoring to track optimization impact
  6. Continuous Improvement: Regular review and refinement of optimization strategies

Conclusion

MongoDB's advanced query optimization and explain plan system provides comprehensive tools for identifying performance bottlenecks, analyzing query execution patterns, and implementing effective optimization strategies. The sophisticated explain functionality offers detailed insights that enable both development and production performance tuning with automated recommendations and historical analysis capabilities.

Key MongoDB Query Optimization benefits include:

  • Comprehensive Analysis: Detailed execution plan analysis with performance metrics and bottleneck identification
  • Automated Recommendations: Intelligent optimization suggestions based on query patterns and performance data
  • Real-time Monitoring: Continuous performance monitoring with alerting and trend analysis
  • Production-Ready Tools: Sophisticated analysis tools designed for production database optimization
  • Historical Intelligence: Performance trend analysis and regression detection capabilities
  • Integration-Friendly: Seamless integration with existing monitoring and alerting infrastructure

Whether you're optimizing application queries, managing database performance, or implementing automated optimization workflows, MongoDB's query optimization tools with QueryLeaf's familiar SQL interface provide the foundation for high-performance database operations.

QueryLeaf Integration: QueryLeaf automatically manages MongoDB query optimization while providing SQL-familiar explain plan syntax, performance analysis functions, and optimization recommendations. Advanced query analysis patterns, automated optimization workflows, and comprehensive performance monitoring are seamlessly handled through familiar SQL constructs, making sophisticated database optimization both powerful and accessible to SQL-oriented development teams.

The combination of comprehensive query analysis capabilities with SQL-style operations makes MongoDB an ideal platform for applications requiring both high-performance queries and familiar database optimization patterns, ensuring your applications achieve optimal performance while remaining maintainable as they scale and evolve.

MongoDB Document Validation and Schema Enforcement: Building Data Integrity with Flexible Schema Design and SQL-Style Constraints

Modern applications require the flexibility of document databases while maintaining data integrity and consistency that traditional relational systems provide through rigid schemas and constraints. MongoDB's document validation system bridges this gap by offering configurable schema enforcement that adapts to evolving business requirements without sacrificing data quality.

MongoDB Document Validation provides rule-based data validation that can enforce structure, data types, value ranges, and business logic constraints at the database level. Unlike rigid relational schemas that require expensive migrations for changes, MongoDB validation rules can evolve incrementally, supporting both strict schema enforcement and flexible document structures within the same database.

The Traditional Schema Rigidity Challenge

Conventional relational database approaches impose inflexible schema constraints that become obstacles to application evolution:

-- Traditional PostgreSQL schema with rigid constraints and migration challenges

-- User table with fixed schema structure
CREATE TABLE users (
  user_id BIGSERIAL PRIMARY KEY,
  email VARCHAR(255) NOT NULL UNIQUE,
  username VARCHAR(50) NOT NULL UNIQUE,
  password_hash VARCHAR(255) NOT NULL,
  first_name VARCHAR(100) NOT NULL,
  last_name VARCHAR(100) NOT NULL,
  birth_date DATE,
  phone_number VARCHAR(20),
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),

  -- Rigid constraints that are difficult to modify
  CONSTRAINT users_email_format CHECK (email ~* '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}$'),
  CONSTRAINT users_phone_format CHECK (phone_number ~* '^\+?[1-9]\d{1,14}$'),
  CONSTRAINT users_birth_date_range CHECK (birth_date >= '1900-01-01' AND birth_date <= CURRENT_DATE),
  CONSTRAINT users_name_length CHECK (LENGTH(first_name) >= 2 AND LENGTH(last_name) >= 2)
);

-- User profile table with limited JSON support
CREATE TABLE user_profiles (
  profile_id BIGSERIAL PRIMARY KEY,
  user_id BIGINT NOT NULL REFERENCES users(user_id) ON DELETE CASCADE,
  bio TEXT,
  avatar_url VARCHAR(500),
  social_links JSONB,
  preferences JSONB,
  metadata JSONB,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),

  -- Limited JSON validation capabilities
  CONSTRAINT profile_bio_length CHECK (LENGTH(bio) <= 1000),
  CONSTRAINT profile_avatar_url_format CHECK (avatar_url ~* '^https?://.*'),
  CONSTRAINT profile_social_links_structure CHECK (
    social_links IS NULL OR (
      jsonb_typeof(social_links) = 'object' AND
      jsonb_array_length(jsonb_object_keys(social_links)) <= 10
    )
  )
);

-- User settings table with enum constraints
CREATE TYPE notification_frequency AS ENUM ('immediate', 'hourly', 'daily', 'weekly', 'never');
CREATE TYPE privacy_level AS ENUM ('public', 'friends', 'private');
CREATE TYPE theme_preference AS ENUM ('light', 'dark', 'auto');

CREATE TABLE user_settings (
  setting_id BIGSERIAL PRIMARY KEY,
  user_id BIGINT NOT NULL REFERENCES users(user_id) ON DELETE CASCADE,
  email_notifications notification_frequency DEFAULT 'daily',
  push_notifications notification_frequency DEFAULT 'immediate',
  privacy_level privacy_level DEFAULT 'friends',
  theme theme_preference DEFAULT 'auto',
  language_code VARCHAR(5) DEFAULT 'en-US',
  timezone VARCHAR(50) DEFAULT 'UTC',
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),

  -- Rigid enum constraints that require schema changes
  CONSTRAINT settings_language_format CHECK (language_code ~* '^[a-z]{2}(-[A-Z]{2})?$'),
  CONSTRAINT settings_timezone_valid CHECK (timezone IN (
    SELECT name FROM pg_timezone_names WHERE name NOT LIKE '%/%/%'
  ))
);

-- Complex data insertion with rigid validation
INSERT INTO users (
  email, username, password_hash, first_name, last_name, birth_date, phone_number
) VALUES (
  '[email protected]',
  'johndoe123',
  '$2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewdBxJzybKlJNcX.',
  'John',
  'Doe', 
  '1990-05-15',
  '+1-555-123-4567'
);

-- Profile insertion with limited JSON flexibility
INSERT INTO user_profiles (
  user_id, bio, avatar_url, social_links, preferences, metadata
) VALUES (
  1,
  'Software engineer passionate about technology and innovation.',
  'https://example.com/avatars/johndoe.jpg',
  '{"twitter": "@johndoe", "linkedin": "john-doe-dev", "github": "johndoe"}',
  '{"newsletter": true, "marketing_emails": false, "beta_features": true}',
  '{"account_type": "premium", "registration_source": "web", "referral_code": "FRIEND123"}'
);

-- Settings insertion with enum constraints
INSERT INTO user_settings (
  user_id, email_notifications, push_notifications, privacy_level, theme, language_code, timezone
) VALUES (
  1, 'daily', 'immediate', 'friends', 'dark', 'en-US', 'America/New_York'
);

-- Complex query with multiple table joins and JSON operations
WITH user_analysis AS (
  SELECT 
    u.user_id,
    u.email,
    u.username,
    u.first_name,
    u.last_name,
    u.created_at as registration_date,

    -- Profile information with JSON extraction
    up.bio,
    up.avatar_url,
    jsonb_extract_path_text(up.social_links, 'twitter') as twitter_handle,
    jsonb_extract_path_text(up.social_links, 'github') as github_username,

    -- Preferences with type casting
    CAST(jsonb_extract_path_text(up.preferences, 'newsletter') AS BOOLEAN) as newsletter_subscription,
    CAST(jsonb_extract_path_text(up.preferences, 'beta_features') AS BOOLEAN) as beta_participant,

    -- Metadata extraction
    jsonb_extract_path_text(up.metadata, 'account_type') as account_type,
    jsonb_extract_path_text(up.metadata, 'registration_source') as registration_source,

    -- Settings information
    us.email_notifications,
    us.push_notifications,
    us.privacy_level,
    us.theme,
    us.language_code,
    us.timezone,

    -- Calculated fields
    EXTRACT(YEAR FROM AGE(u.birth_date)) as age,
    EXTRACT(DAYS FROM (NOW() - u.created_at)) as days_since_registration,

    -- JSON array processing for social links
    jsonb_array_length(jsonb_object_keys(COALESCE(up.social_links, '{}'::jsonb))) as social_link_count,

    -- Complex JSON validation checking
    CASE 
      WHEN up.preferences IS NULL THEN 'incomplete'
      WHEN jsonb_typeof(up.preferences) != 'object' THEN 'invalid'
      WHEN NOT up.preferences ? 'newsletter' THEN 'missing_required'
      ELSE 'valid'
    END as preferences_status

  FROM users u
  LEFT JOIN user_profiles up ON u.user_id = up.user_id
  LEFT JOIN user_settings us ON u.user_id = us.user_id
  WHERE u.created_at >= NOW() - INTERVAL '1 year'
)

SELECT 
  user_id,
  email,
  username,
  first_name || ' ' || last_name as full_name,
  registration_date,
  bio,
  twitter_handle,
  github_username,
  account_type,
  registration_source,
  age,
  days_since_registration,

  -- User categorization based on engagement
  CASE 
    WHEN beta_participant AND newsletter_subscription THEN 'highly_engaged'
    WHEN newsletter_subscription OR social_link_count > 2 THEN 'moderately_engaged' 
    WHEN days_since_registration < 30 THEN 'new_user'
    ELSE 'basic_user'
  END as engagement_level,

  -- Notification preference summary
  CASE 
    WHEN email_notifications = 'immediate' AND push_notifications = 'immediate' THEN 'high_frequency'
    WHEN email_notifications IN ('daily', 'hourly') OR push_notifications IN ('daily', 'hourly') THEN 'moderate_frequency'
    ELSE 'low_frequency'
  END as notification_preference,

  -- Data completeness assessment
  CASE 
    WHEN bio IS NOT NULL AND avatar_url IS NOT NULL AND social_link_count > 0 THEN 'complete'
    WHEN bio IS NOT NULL OR avatar_url IS NOT NULL THEN 'partial'
    ELSE 'minimal'
  END as profile_completeness,

  preferences_status

FROM user_analysis
WHERE preferences_status = 'valid'
ORDER BY 
  CASE engagement_level
    WHEN 'highly_engaged' THEN 1
    WHEN 'moderately_engaged' THEN 2  
    WHEN 'new_user' THEN 3
    ELSE 4
  END,
  days_since_registration DESC;

-- Schema evolution challenges with traditional approaches:
-- 1. Adding new fields requires ALTER TABLE statements with potential downtime
-- 2. Changing data types requires complex migrations and data conversion
-- 3. Enum modifications require dropping and recreating types
-- 4. JSON structure changes are difficult to validate and enforce
-- 5. Cross-table constraints become complex to maintain
-- 6. Schema changes require coordinated application deployments
-- 7. Rollback of schema changes is complex and often impossible
-- 8. Performance impact during large table alterations
-- 9. Limited flexibility for storing varying document structures
-- 10. Complex validation logic requires triggers or application-level enforcement

-- MySQL approach with even more limitations
CREATE TABLE mysql_users (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  email VARCHAR(255) NOT NULL UNIQUE,
  username VARCHAR(50) NOT NULL UNIQUE,
  profile_data JSON,
  settings JSON,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

  -- Basic JSON validation (limited in older versions)
  CONSTRAINT email_format CHECK (email REGEXP '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$')
);

-- Simple query with limited JSON capabilities
SELECT 
  id,
  email,
  username,
  JSON_EXTRACT(profile_data, '$.first_name') as first_name,
  JSON_EXTRACT(profile_data, '$.last_name') as last_name,
  JSON_EXTRACT(settings, '$.theme') as theme_preference
FROM mysql_users
WHERE JSON_EXTRACT(profile_data, '$.account_type') = 'premium';

-- MySQL limitations:
-- - Very limited JSON validation and constraint capabilities
-- - Basic JSON functions with poor performance on large datasets
-- - No sophisticated document structure validation
-- - Minimal support for nested object validation
-- - Limited flexibility for evolving JSON schemas
-- - Poor indexing support for JSON fields
-- - Basic constraint checking without complex business logic

MongoDB Document Validation provides flexible, powerful schema enforcement:

// MongoDB Document Validation - flexible schema enforcement with powerful validation rules
const { MongoClient } = require('mongodb');

const client = new MongoClient('mongodb://localhost:27017');
const db = client.db('user_management_platform');

// Comprehensive document validation and schema management system
class MongoDBValidationManager {
  constructor(db) {
    this.db = db;
    this.collections = new Map();
    this.validationRules = new Map();
    this.migrationHistory = [];
  }

  async initializeCollectionsWithValidation() {
    console.log('Initializing collections with comprehensive document validation...');

    // Create users collection with sophisticated validation rules
    try {
      await this.db.createCollection('users', {
        validator: {
          $jsonSchema: {
            bsonType: 'object',
            required: ['email', 'username', 'password_hash', 'profile', 'created_at'],
            additionalProperties: false,
            properties: {
              _id: {
                bsonType: 'objectId'
              },

              // Core identity fields with validation
              email: {
                bsonType: 'string',
                pattern: '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$',
                description: 'Valid email address required'
              },

              username: {
                bsonType: 'string',
                minLength: 3,
                maxLength: 30,
                pattern: '^[a-zA-Z0-9_-]+$',
                description: 'Username must be 3-30 characters, alphanumeric with underscore/dash'
              },

              password_hash: {
                bsonType: 'string',
                minLength: 60,
                maxLength: 60,
                description: 'BCrypt hash must be exactly 60 characters'
              },

              // Nested profile object with detailed validation
              profile: {
                bsonType: 'object',
                required: ['first_name', 'last_name'],
                additionalProperties: true,
                properties: {
                  first_name: {
                    bsonType: 'string',
                    minLength: 1,
                    maxLength: 100,
                    description: 'First name is required'
                  },

                  last_name: {
                    bsonType: 'string',
                    minLength: 1,
                    maxLength: 100,
                    description: 'Last name is required'
                  },

                  middle_name: {
                    bsonType: ['string', 'null'],
                    maxLength: 100
                  },

                  birth_date: {
                    bsonType: 'date',
                    description: 'Birth date must be a valid date'
                  },

                  phone_number: {
                    bsonType: ['string', 'null'],
                    pattern: '^\\+?[1-9]\\d{1,14}$',
                    description: 'Valid international phone number format'
                  },

                  bio: {
                    bsonType: ['string', 'null'],
                    maxLength: 1000,
                    description: 'Bio must not exceed 1000 characters'
                  },

                  avatar_url: {
                    bsonType: ['string', 'null'],
                    pattern: '^https?://.*\\.(jpg|jpeg|png|gif|webp)$',
                    description: 'Avatar must be a valid image URL'
                  },

                  // Social links with nested validation
                  social_links: {
                    bsonType: ['object', 'null'],
                    additionalProperties: false,
                    properties: {
                      twitter: {
                        bsonType: 'string',
                        pattern: '^@?[a-zA-Z0-9_]{1,15}$'
                      },
                      linkedin: {
                        bsonType: 'string',
                        pattern: '^[a-zA-Z0-9-]{3,100}$'
                      },
                      github: {
                        bsonType: 'string',
                        pattern: '^[a-zA-Z0-9-]{1,39}$'
                      },
                      website: {
                        bsonType: 'string',
                        pattern: '^https?://[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}.*$'
                      },
                      instagram: {
                        bsonType: 'string',
                        pattern: '^@?[a-zA-Z0-9_.]{1,30}$'
                      }
                    }
                  },

                  // Address with geolocation support
                  address: {
                    bsonType: ['object', 'null'],
                    properties: {
                      street: { bsonType: 'string', maxLength: 200 },
                      city: { bsonType: 'string', maxLength: 100 },
                      state: { bsonType: 'string', maxLength: 100 },
                      postal_code: { bsonType: 'string', maxLength: 20 },
                      country: { bsonType: 'string', maxLength: 100 },
                      coordinates: {
                        bsonType: 'object',
                        properties: {
                          type: { enum: ['Point'] },
                          coordinates: {
                            bsonType: 'array',
                            minItems: 2,
                            maxItems: 2,
                            items: { bsonType: 'number' }
                          }
                        }
                      }
                    }
                  }
                }
              },

              // User preferences with detailed validation
              preferences: {
                bsonType: 'object',
                additionalProperties: true,
                properties: {
                  notifications: {
                    bsonType: 'object',
                    properties: {
                      email: {
                        bsonType: 'object',
                        properties: {
                          marketing: { bsonType: 'bool' },
                          security: { bsonType: 'bool' },
                          product_updates: { bsonType: 'bool' },
                          frequency: { enum: ['immediate', 'daily', 'weekly', 'never'] }
                        }
                      },
                      push: {
                        bsonType: 'object',
                        properties: {
                          enabled: { bsonType: 'bool' },
                          sound: { bsonType: 'bool' },
                          vibration: { bsonType: 'bool' },
                          frequency: { enum: ['immediate', 'hourly', 'daily', 'never'] }
                        }
                      }
                    }
                  },

                  privacy: {
                    bsonType: 'object',
                    properties: {
                      profile_visibility: { enum: ['public', 'friends', 'private'] },
                      search_visibility: { bsonType: 'bool' },
                      activity_status: { bsonType: 'bool' },
                      data_collection: { bsonType: 'bool' }
                    }
                  },

                  interface: {
                    bsonType: 'object',
                    properties: {
                      theme: { enum: ['light', 'dark', 'auto'] },
                      language: {
                        bsonType: 'string',
                        pattern: '^[a-z]{2}(-[A-Z]{2})?$'
                      },
                      timezone: {
                        bsonType: 'string',
                        description: 'Valid IANA timezone'
                      },
                      date_format: { enum: ['MM/DD/YYYY', 'DD/MM/YYYY', 'YYYY-MM-DD'] },
                      time_format: { enum: ['12h', '24h'] }
                    }
                  }
                }
              },

              // Account status and metadata
              account: {
                bsonType: 'object',
                required: ['status', 'type', 'verification'],
                properties: {
                  status: { enum: ['active', 'inactive', 'suspended', 'pending'] },
                  type: { enum: ['free', 'premium', 'enterprise', 'admin'] },
                  subscription_expires_at: { bsonType: ['date', 'null'] },

                  verification: {
                    bsonType: 'object',
                    properties: {
                      email_verified: { bsonType: 'bool' },
                      email_verified_at: { bsonType: ['date', 'null'] },
                      phone_verified: { bsonType: 'bool' },
                      phone_verified_at: { bsonType: ['date', 'null'] },
                      identity_verified: { bsonType: 'bool' },
                      identity_verified_at: { bsonType: ['date', 'null'] },
                      verification_level: { enum: ['none', 'email', 'phone', 'identity', 'full'] }
                    }
                  },

                  security: {
                    bsonType: 'object',
                    properties: {
                      two_factor_enabled: { bsonType: 'bool' },
                      two_factor_method: { enum: ['none', 'sms', 'app', 'email'] },
                      password_changed_at: { bsonType: 'date' },
                      last_password_reset: { bsonType: ['date', 'null'] },
                      failed_login_attempts: { bsonType: 'int', minimum: 0, maximum: 10 },
                      account_locked_until: { bsonType: ['date', 'null'] }
                    }
                  }
                }
              },

              // Activity tracking
              activity: {
                bsonType: 'object',
                properties: {
                  last_login_at: { bsonType: ['date', 'null'] },
                  last_activity_at: { bsonType: ['date', 'null'] },
                  login_count: { bsonType: 'int', minimum: 0 },
                  session_count: { bsonType: 'int', minimum: 0 },
                  ip_address: {
                    bsonType: ['string', 'null'],
                    pattern: '^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$|^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$'
                  },
                  user_agent: { bsonType: ['string', 'null'], maxLength: 500 }
                }
              },

              // Flexible metadata for application-specific data
              metadata: {
                bsonType: ['object', 'null'],
                additionalProperties: true,
                properties: {
                  registration_source: {
                    enum: ['web', 'mobile_app', 'api', 'admin', 'import', 'social_oauth']
                  },
                  referral_code: {
                    bsonType: ['string', 'null'],
                    pattern: '^[A-Z0-9]{6,12}$'
                  },
                  campaign_id: { bsonType: ['string', 'null'] },
                  utm_source: { bsonType: ['string', 'null'] },
                  utm_medium: { bsonType: ['string', 'null'] },
                  utm_campaign: { bsonType: ['string', 'null'] },
                  affiliate_id: { bsonType: ['string', 'null'] }
                }
              },

              // Audit timestamps
              created_at: {
                bsonType: 'date',
                description: 'Account creation timestamp required'
              },

              updated_at: {
                bsonType: 'date',
                description: 'Last update timestamp'
              },

              deleted_at: {
                bsonType: ['date', 'null'],
                description: 'Soft delete timestamp'
              }
            }
          }
        },
        validationLevel: 'strict',
        validationAction: 'error'
      });

      console.log('Created users collection with comprehensive validation');
      this.collections.set('users', this.db.collection('users'));

    } catch (error) {
      if (error.code !== 48) { // Collection already exists
        throw error;
      }
      console.log('Users collection already exists');
      this.collections.set('users', this.db.collection('users'));
    }

    // Create additional collections with validation
    await this.createSessionsCollection();
    await this.createAuditLogCollection();
    await this.createNotificationsCollection();

    // Create indexes optimized for validation and queries
    await this.createOptimizedIndexes();

    return Array.from(this.collections.keys());
  }

  async createSessionsCollection() {
    try {
      await this.db.createCollection('user_sessions', {
        validator: {
          $jsonSchema: {
            bsonType: 'object',
            required: ['user_id', 'session_token', 'created_at', 'expires_at', 'is_active'],
            properties: {
              _id: { bsonType: 'objectId' },

              user_id: {
                bsonType: 'objectId',
                description: 'Reference to user document'
              },

              session_token: {
                bsonType: 'string',
                minLength: 32,
                maxLength: 128,
                description: 'Secure session token'
              },

              refresh_token: {
                bsonType: ['string', 'null'],
                minLength: 32,
                maxLength: 128
              },

              device_info: {
                bsonType: 'object',
                properties: {
                  device_type: { enum: ['desktop', 'mobile', 'tablet', 'unknown'] },
                  browser: { bsonType: 'string', maxLength: 100 },
                  os: { bsonType: 'string', maxLength: 100 },
                  ip_address: { bsonType: 'string' },
                  user_agent: { bsonType: 'string', maxLength: 500 }
                }
              },

              location: {
                bsonType: ['object', 'null'],
                properties: {
                  country: { bsonType: 'string', maxLength: 100 },
                  region: { bsonType: 'string', maxLength: 100 },
                  city: { bsonType: 'string', maxLength: 100 },
                  coordinates: {
                    bsonType: 'array',
                    minItems: 2,
                    maxItems: 2,
                    items: { bsonType: 'number' }
                  }
                }
              },

              is_active: { bsonType: 'bool' },

              created_at: { bsonType: 'date' },
              updated_at: { bsonType: 'date' },
              expires_at: { bsonType: 'date' },
              last_activity_at: { bsonType: ['date', 'null'] }
            }
          }
        },
        validationLevel: 'strict'
      });

      // Create TTL index for automatic session cleanup
      await this.db.collection('user_sessions').createIndex(
        { expires_at: 1 }, 
        { expireAfterSeconds: 0 }
      );

      this.collections.set('user_sessions', this.db.collection('user_sessions'));
      console.log('Created user_sessions collection with validation');

    } catch (error) {
      if (error.code !== 48) throw error;
      this.collections.set('user_sessions', this.db.collection('user_sessions'));
    }
  }

  async createAuditLogCollection() {
    try {
      await this.db.createCollection('audit_log', {
        validator: {
          $jsonSchema: {
            bsonType: 'object',
            required: ['user_id', 'action', 'resource_type', 'timestamp'],
            properties: {
              _id: { bsonType: 'objectId' },

              user_id: {
                bsonType: ['objectId', 'null'],
                description: 'User who performed the action'
              },

              action: {
                enum: [
                  'create', 'read', 'update', 'delete',
                  'login', 'logout', 'password_change', 'email_change',
                  'profile_update', 'settings_change', 'verification',
                  'admin_action', 'api_access', 'export_data'
                ],
                description: 'Type of action performed'
              },

              resource_type: {
                bsonType: 'string',
                maxLength: 100,
                description: 'Type of resource affected'
              },

              resource_id: {
                bsonType: ['string', 'objectId', 'null'],
                description: 'ID of the affected resource'
              },

              details: {
                bsonType: ['object', 'null'],
                additionalProperties: true,
                description: 'Additional action details'
              },

              changes: {
                bsonType: ['object', 'null'],
                properties: {
                  before: { bsonType: ['object', 'null'] },
                  after: { bsonType: ['object', 'null'] },
                  fields_changed: {
                    bsonType: 'array',
                    items: { bsonType: 'string' }
                  }
                }
              },

              request_info: {
                bsonType: ['object', 'null'],
                properties: {
                  ip_address: { bsonType: 'string' },
                  user_agent: { bsonType: 'string', maxLength: 500 },
                  method: { enum: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] },
                  endpoint: { bsonType: 'string', maxLength: 200 },
                  session_id: { bsonType: ['string', 'null'] }
                }
              },

              result: {
                bsonType: 'object',
                properties: {
                  success: { bsonType: 'bool' },
                  error_message: { bsonType: ['string', 'null'] },
                  error_code: { bsonType: ['string', 'null'] },
                  duration_ms: { bsonType: 'int', minimum: 0 }
                }
              },

              timestamp: { bsonType: 'date' }
            }
          }
        }
      });

      this.collections.set('audit_log', this.db.collection('audit_log'));
      console.log('Created audit_log collection with validation');

    } catch (error) {
      if (error.code !== 48) throw error;
      this.collections.set('audit_log', this.db.collection('audit_log'));
    }
  }

  async createNotificationsCollection() {
    try {
      await this.db.createCollection('notifications', {
        validator: {
          $jsonSchema: {
            bsonType: 'object',
            required: ['user_id', 'type', 'title', 'content', 'status', 'created_at'],
            properties: {
              _id: { bsonType: 'objectId' },

              user_id: {
                bsonType: 'objectId',
                description: 'Target user for notification'
              },

              type: {
                enum: [
                  'security_alert', 'account_update', 'welcome', 'verification',
                  'password_reset', 'login_alert', 'subscription', 'feature_announcement',
                  'maintenance', 'privacy_update', 'marketing', 'system'
                ],
                description: 'Notification category'
              },

              priority: {
                enum: ['low', 'normal', 'high', 'urgent'],
                description: 'Notification priority level'
              },

              title: {
                bsonType: 'string',
                minLength: 1,
                maxLength: 200,
                description: 'Notification title'
              },

              content: {
                bsonType: 'string',
                minLength: 1,
                maxLength: 2000,
                description: 'Notification message content'
              },

              action: {
                bsonType: ['object', 'null'],
                properties: {
                  label: { bsonType: 'string', maxLength: 50 },
                  url: { bsonType: 'string', maxLength: 500 },
                  action_type: { enum: ['link', 'button', 'dismiss', 'confirm'] }
                }
              },

              channels: {
                bsonType: 'array',
                items: {
                  enum: ['email', 'push', 'in_app', 'sms', 'webhook']
                },
                description: 'Delivery channels for notification'
              },

              delivery: {
                bsonType: 'object',
                properties: {
                  email: {
                    bsonType: ['object', 'null'],
                    properties: {
                      sent_at: { bsonType: ['date', 'null'] },
                      delivered_at: { bsonType: ['date', 'null'] },
                      opened_at: { bsonType: ['date', 'null'] },
                      clicked_at: { bsonType: ['date', 'null'] },
                      bounced: { bsonType: 'bool' },
                      error_message: { bsonType: ['string', 'null'] }
                    }
                  },
                  push: {
                    bsonType: ['object', 'null'],
                    properties: {
                      sent_at: { bsonType: ['date', 'null'] },
                      delivered_at: { bsonType: ['date', 'null'] },
                      clicked_at: { bsonType: ['date', 'null'] },
                      error_message: { bsonType: ['string', 'null'] }
                    }
                  },
                  in_app: {
                    bsonType: ['object', 'null'],
                    properties: {
                      shown_at: { bsonType: ['date', 'null'] },
                      clicked_at: { bsonType: ['date', 'null'] },
                      dismissed_at: { bsonType: ['date', 'null'] }
                    }
                  }
                }
              },

              status: {
                enum: ['pending', 'sent', 'delivered', 'read', 'dismissed', 'failed'],
                description: 'Current notification status'
              },

              metadata: {
                bsonType: ['object', 'null'],
                additionalProperties: true,
                description: 'Additional notification metadata'
              },

              expires_at: {
                bsonType: ['date', 'null'],
                description: 'Notification expiration date'
              },

              created_at: { bsonType: 'date' },
              updated_at: { bsonType: 'date' }
            }
          }
        }
      });

      this.collections.set('notifications', this.db.collection('notifications'));
      console.log('Created notifications collection with validation');

    } catch (error) {
      if (error.code !== 48) throw error;
      this.collections.set('notifications', this.db.collection('notifications'));
    }
  }

  async createOptimizedIndexes() {
    console.log('Creating optimized indexes for validated collections...');

    const users = this.collections.get('users');
    const sessions = this.collections.get('user_sessions');
    const audit = this.collections.get('audit_log');
    const notifications = this.collections.get('notifications');

    // User collection indexes
    const userIndexes = [
      { email: 1 },
      { username: 1 },
      { 'account.status': 1 },
      { 'account.type': 1 },
      { created_at: -1 },
      { 'activity.last_login_at': -1 },
      { 'profile.phone_number': 1 },
      { 'account.verification.email_verified': 1 },
      { 'metadata.registration_source': 1 },

      // Compound indexes for common queries
      { 'account.status': 1, 'account.type': 1 },
      { 'account.type': 1, created_at: -1 },
      { 'account.verification.verification_level': 1, created_at: -1 }
    ];

    for (const indexSpec of userIndexes) {
      try {
        await users.createIndex(indexSpec, { background: true });
      } catch (error) {
        console.warn('Index creation warning:', error.message);
      }
    }

    // Session collection indexes
    await sessions.createIndex({ user_id: 1, is_active: 1 }, { background: true });
    await sessions.createIndex({ session_token: 1 }, { unique: true, background: true });
    await sessions.createIndex({ created_at: -1 }, { background: true });

    // Audit log indexes
    await audit.createIndex({ user_id: 1, timestamp: -1 }, { background: true });
    await audit.createIndex({ action: 1, timestamp: -1 }, { background: true });
    await audit.createIndex({ resource_type: 1, resource_id: 1 }, { background: true });

    // Notification indexes
    await notifications.createIndex({ user_id: 1, status: 1 }, { background: true });
    await notifications.createIndex({ type: 1, created_at: -1 }, { background: true });
    await notifications.createIndex({ expires_at: 1 }, { expireAfterSeconds: 0 });

    console.log('Optimized indexes created successfully');
  }

  async insertValidatedUserData(userData) {
    console.log('Inserting user data with comprehensive validation...');

    const users = this.collections.get('users');
    const currentTime = new Date();

    // Prepare validated user document
    const validatedUser = {
      email: userData.email,
      username: userData.username,
      password_hash: userData.password_hash,

      profile: {
        first_name: userData.profile.first_name,
        last_name: userData.profile.last_name,
        middle_name: userData.profile.middle_name || null,
        birth_date: userData.profile.birth_date ? new Date(userData.profile.birth_date) : null,
        phone_number: userData.profile.phone_number || null,
        bio: userData.profile.bio || null,
        avatar_url: userData.profile.avatar_url || null,

        social_links: userData.profile.social_links || null,

        address: userData.profile.address ? {
          street: userData.profile.address.street,
          city: userData.profile.address.city,
          state: userData.profile.address.state,
          postal_code: userData.profile.address.postal_code,
          country: userData.profile.address.country,
          coordinates: userData.profile.address.coordinates ? {
            type: 'Point',
            coordinates: userData.profile.address.coordinates
          } : null
        } : null
      },

      preferences: {
        notifications: {
          email: {
            marketing: userData.preferences?.notifications?.email?.marketing ?? false,
            security: userData.preferences?.notifications?.email?.security ?? true,
            product_updates: userData.preferences?.notifications?.email?.product_updates ?? true,
            frequency: userData.preferences?.notifications?.email?.frequency || 'daily'
          },
          push: {
            enabled: userData.preferences?.notifications?.push?.enabled ?? true,
            sound: userData.preferences?.notifications?.push?.sound ?? true,
            vibration: userData.preferences?.notifications?.push?.vibration ?? true,
            frequency: userData.preferences?.notifications?.push?.frequency || 'immediate'
          }
        },

        privacy: {
          profile_visibility: userData.preferences?.privacy?.profile_visibility || 'friends',
          search_visibility: userData.preferences?.privacy?.search_visibility ?? true,
          activity_status: userData.preferences?.privacy?.activity_status ?? true,
          data_collection: userData.preferences?.privacy?.data_collection ?? true
        },

        interface: {
          theme: userData.preferences?.interface?.theme || 'auto',
          language: userData.preferences?.interface?.language || 'en-US',
          timezone: userData.preferences?.interface?.timezone || 'UTC',
          date_format: userData.preferences?.interface?.date_format || 'MM/DD/YYYY',
          time_format: userData.preferences?.interface?.time_format || '12h'
        }
      },

      account: {
        status: userData.account?.status || 'active',
        type: userData.account?.type || 'free',
        subscription_expires_at: userData.account?.subscription_expires_at ? 
          new Date(userData.account.subscription_expires_at) : null,

        verification: {
          email_verified: false,
          email_verified_at: null,
          phone_verified: false,
          phone_verified_at: null,
          identity_verified: false,
          identity_verified_at: null,
          verification_level: 'none'
        },

        security: {
          two_factor_enabled: false,
          two_factor_method: 'none',
          password_changed_at: currentTime,
          last_password_reset: null,
          failed_login_attempts: 0,
          account_locked_until: null
        }
      },

      activity: {
        last_login_at: null,
        last_activity_at: null,
        login_count: 0,
        session_count: 0,
        ip_address: userData.activity?.ip_address || null,
        user_agent: userData.activity?.user_agent || null
      },

      metadata: userData.metadata || null,

      created_at: currentTime,
      updated_at: currentTime,
      deleted_at: null
    };

    try {
      const result = await users.insertOne(validatedUser);

      // Log successful user creation
      await this.logAuditEvent({
        user_id: result.insertedId,
        action: 'create',
        resource_type: 'user',
        resource_id: result.insertedId.toString(),
        details: {
          username: validatedUser.username,
          email: validatedUser.email,
          account_type: validatedUser.account.type
        },
        request_info: {
          ip_address: validatedUser.activity.ip_address,
          user_agent: validatedUser.activity.user_agent
        },
        result: {
          success: true,
          duration_ms: 0 // Would be calculated in real implementation
        },
        timestamp: currentTime
      });

      console.log(`User created successfully with ID: ${result.insertedId}`);
      return result;

    } catch (validationError) {
      console.error('User validation failed:', validationError);

      // Log failed user creation attempt
      await this.logAuditEvent({
        user_id: null,
        action: 'create',
        resource_type: 'user',
        details: {
          attempted_email: userData.email,
          attempted_username: userData.username
        },
        result: {
          success: false,
          error_message: validationError.message,
          error_code: validationError.code?.toString()
        },
        timestamp: currentTime
      });

      throw validationError;
    }
  }

  async logAuditEvent(eventData) {
    const auditLog = this.collections.get('audit_log');

    try {
      await auditLog.insertOne(eventData);
    } catch (error) {
      console.warn('Failed to log audit event:', error.message);
    }
  }

  async performValidationMigration(collectionName, newValidationRules, options = {}) {
    console.log(`Performing validation migration for collection: ${collectionName}`);

    const {
      validationLevel = 'strict',
      validationAction = 'error',
      dryRun = false,
      batchSize = 1000
    } = options;

    const collection = this.db.collection(collectionName);

    if (dryRun) {
      // Test validation rules against existing documents
      console.log('Running dry run validation test...');

      const validationErrors = [];
      let processedCount = 0;

      const cursor = collection.find({}).limit(batchSize);

      for await (const document of cursor) {
        try {
          // Test document against new validation rules (simplified)
          const testResult = await this.testDocumentValidation(document, newValidationRules);

          if (!testResult.valid) {
            validationErrors.push({
              documentId: document._id,
              errors: testResult.errors
            });
          }

          processedCount++;

        } catch (error) {
          validationErrors.push({
            documentId: document._id,
            errors: [error.message]
          });
        }
      }

      console.log(`Dry run completed: ${processedCount} documents tested, ${validationErrors.length} validation errors found`);

      return {
        dryRun: true,
        documentsProcessed: processedCount,
        validationErrors: validationErrors,
        migrationFeasible: validationErrors.length === 0
      };
    }

    // Apply new validation rules
    try {
      await this.db.runCommand({
        collMod: collectionName,
        validator: newValidationRules,
        validationLevel: validationLevel,
        validationAction: validationAction
      });

      // Record migration in history
      this.migrationHistory.push({
        collection: collectionName,
        timestamp: new Date(),
        validationRules: newValidationRules,
        validationLevel: validationLevel,
        validationAction: validationAction,
        success: true
      });

      console.log(`Validation migration completed successfully for ${collectionName}`);

      return {
        success: true,
        collection: collectionName,
        timestamp: new Date(),
        validationLevel: validationLevel,
        validationAction: validationAction
      };

    } catch (error) {
      console.error('Validation migration failed:', error);

      this.migrationHistory.push({
        collection: collectionName,
        timestamp: new Date(),
        success: false,
        error: error.message
      });

      throw error;
    }
  }

  async testDocumentValidation(document, validationRules) {
    // Simplified validation testing (in real implementation, would use MongoDB's validator)
    try {
      // This would use MongoDB's internal validation logic
      return { valid: true, errors: [] };
    } catch (error) {
      return { valid: false, errors: [error.message] };
    }
  }

  async generateValidationReport() {
    console.log('Generating comprehensive validation report...');

    const report = {
      collections: new Map(),
      summary: {
        totalCollections: 0,
        validatedCollections: 0,
        totalDocuments: 0,
        validationCoverage: 0
      },
      recommendations: []
    };

    for (const [collectionName, collection] of this.collections) {
      console.log(`Analyzing validation for collection: ${collectionName}`);

      try {
        // Get collection info including validation rules
        const collectionInfo = await this.db.runCommand({ listCollections: { filter: { name: collectionName } } });
        const stats = await collection.stats();

        const collectionData = {
          name: collectionName,
          documentCount: stats.count,
          avgDocumentSize: stats.avgObjSize,
          indexCount: stats.nindexes,
          hasValidation: false,
          validationLevel: null,
          validationAction: null,
          validationRules: null
        };

        // Check if validation is configured
        if (collectionInfo.cursor.firstBatch[0]?.options?.validator) {
          collectionData.hasValidation = true;
          collectionData.validationLevel = collectionInfo.cursor.firstBatch[0].options.validationLevel || 'strict';
          collectionData.validationAction = collectionInfo.cursor.firstBatch[0].options.validationAction || 'error';
          collectionData.validationRules = collectionInfo.cursor.firstBatch[0].options.validator;
        }

        report.collections.set(collectionName, collectionData);
        report.summary.totalCollections++;
        report.summary.totalDocuments += stats.count;

        if (collectionData.hasValidation) {
          report.summary.validatedCollections++;
        }

        // Generate recommendations
        if (!collectionData.hasValidation && stats.count > 1000) {
          report.recommendations.push(`Consider adding validation rules to ${collectionName} (${stats.count} documents)`);
        }

        if (collectionData.hasValidation && collectionData.validationLevel === 'moderate') {
          report.recommendations.push(`Consider upgrading ${collectionName} to strict validation for better data integrity`);
        }

      } catch (error) {
        console.warn(`Could not analyze collection ${collectionName}:`, error.message);
      }
    }

    report.summary.validationCoverage = report.summary.totalCollections > 0 ? 
      (report.summary.validatedCollections / report.summary.totalCollections * 100) : 0;

    console.log('Validation report generated successfully');
    return report;
  }
}

// Benefits of MongoDB Document Validation:
// - Flexible schema evolution without complex migrations or downtime
// - Rich validation rules supporting nested objects, arrays, and complex business logic
// - Configurable validation levels (strict, moderate, off) for different environments
// - JSON Schema standard compliance with MongoDB-specific extensions
// - Integration with MongoDB's native indexing and query optimization
// - Support for custom validation logic and conditional constraints
// - Gradual validation enforcement for existing data migration scenarios
// - Real-time validation feedback during development and testing
// - Audit trail capabilities for tracking schema changes and validation events
// - Performance optimizations that leverage MongoDB's document-oriented architecture

module.exports = {
  MongoDBValidationManager
};

Understanding MongoDB Document Validation Architecture

Advanced Validation Patterns and Schema Evolution

Implement sophisticated validation strategies for production applications with evolving requirements:

// Advanced document validation patterns and schema evolution strategies
class AdvancedValidationManager {
  constructor(db) {
    this.db = db;
    this.schemaVersions = new Map();
    this.validationProfiles = new Map();
    this.migrationQueue = [];
  }

  async implementConditionalValidation(collectionName, validationProfiles) {
    console.log(`Implementing conditional validation for ${collectionName}`);

    // Create validation rules that adapt based on document type or version
    const conditionalValidator = {
      $or: validationProfiles.map(profile => ({
        $and: [
          profile.condition,
          { $jsonSchema: profile.schema }
        ]
      }))
    };

    await this.db.runCommand({
      collMod: collectionName,
      validator: conditionalValidator,
      validationLevel: 'strict'
    });

    this.validationProfiles.set(collectionName, validationProfiles);
    return conditionalValidator;
  }

  async implementVersionedValidation(collectionName, versions) {
    console.log(`Setting up versioned validation for ${collectionName}`);

    const versionedValidator = {
      $or: versions.map(version => ({
        $and: [
          { schema_version: { $eq: version.version } },
          { $jsonSchema: version.schema }
        ]
      }))
    };

    // Store version history
    this.schemaVersions.set(collectionName, {
      current: Math.max(...versions.map(v => v.version)),
      versions: versions,
      created_at: new Date()
    });

    await this.db.runCommand({
      collMod: collectionName,
      validator: versionedValidator,
      validationLevel: 'strict'
    });

    return versionedValidator;
  }

  async performGradualMigration(collectionName, targetValidation, options = {}) {
    console.log(`Starting gradual migration for ${collectionName}`);

    const {
      batchSize = 1000,
      delayMs = 100,
      validationMode = 'warn_then_error'
    } = options;

    // Phase 1: Warning mode
    if (validationMode === 'warn_then_error') {
      console.log('Phase 1: Enabling validation in warning mode');
      await this.db.runCommand({
        collMod: collectionName,
        validator: targetValidation,
        validationLevel: 'moderate',
        validationAction: 'warn'
      });

      // Allow time for monitoring and fixing validation warnings
      console.log('Monitoring validation warnings for 24 hours...');
      // In production, this would be a longer monitoring period
    }

    // Phase 2: Strict enforcement
    console.log('Phase 2: Enabling strict validation');
    await this.db.runCommand({
      collMod: collectionName,
      validator: targetValidation,
      validationLevel: 'strict',
      validationAction: 'error'
    });

    console.log('Gradual migration completed successfully');
    return { success: true, phases: 2 };
  }

  generateBusinessLogicValidation(rules) {
    // Convert business rules into MongoDB validation expressions
    const validationExpressions = [];

    for (const rule of rules) {
      switch (rule.type) {
        case 'date_range':
          validationExpressions.push({
            [rule.field]: {
              $gte: new Date(rule.min),
              $lte: new Date(rule.max)
            }
          });
          break;

        case 'conditional_required':
          validationExpressions.push({
            $or: [
              { [rule.condition.field]: { $ne: rule.condition.value } },
              { [rule.requiredField]: { $exists: true, $ne: null } }
            ]
          });
          break;

        case 'mutual_exclusion':
          validationExpressions.push({
            $or: rule.fields.map(field => ({ [field]: { $exists: false } }))
              .concat([
                { $expr: { 
                  $lte: [
                    { $size: { $filter: {
                      input: rule.fields,
                      cond: { $ne: [`$$this`, null] }
                    }}},
                    1
                  ]
                }}
              ])
          });
          break;

        case 'cross_field_validation':
          validationExpressions.push({
            $expr: {
              [rule.operator]: [
                `$${rule.field1}`,
                `$${rule.field2}`
              ]
            }
          });
          break;
      }
    }

    return validationExpressions.length > 0 ? { $and: validationExpressions } : {};
  }

  async validateDataQuality(collectionName, qualityRules) {
    console.log(`Running data quality validation for ${collectionName}`);

    const collection = this.db.collection(collectionName);
    const qualityReport = {
      collection: collectionName,
      totalDocuments: await collection.countDocuments(),
      qualityIssues: [],
      qualityScore: 0
    };

    for (const rule of qualityRules) {
      const issueCount = await collection.countDocuments(rule.condition);

      if (issueCount > 0) {
        qualityReport.qualityIssues.push({
          rule: rule.name,
          description: rule.description,
          affectedDocuments: issueCount,
          severity: rule.severity,
          suggestion: rule.suggestion
        });
      }
    }

    // Calculate quality score
    const totalIssues = qualityReport.qualityIssues.reduce((sum, issue) => sum + issue.affectedDocuments, 0);
    qualityReport.qualityScore = Math.max(0, 100 - (totalIssues / qualityReport.totalDocuments * 100));

    return qualityReport;
  }
}

SQL-Style Document Validation with QueryLeaf

QueryLeaf provides familiar SQL syntax for MongoDB document validation and schema management:

-- QueryLeaf document validation with SQL-familiar constraints

-- Create table with comprehensive validation rules
CREATE TABLE users (
  _id ObjectId PRIMARY KEY,
  email VARCHAR(255) NOT NULL UNIQUE 
    CHECK (email REGEXP '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$'),
  username VARCHAR(30) NOT NULL UNIQUE 
    CHECK (username REGEXP '^[a-zA-Z0-9_-]+$' AND LENGTH(username) >= 3),
  password_hash CHAR(60) NOT NULL,

  -- Nested object validation with JSON schema
  profile JSONB NOT NULL CHECK (
    JSON_VALID(profile) AND
    JSON_EXTRACT(profile, '$.first_name') IS NOT NULL AND
    JSON_EXTRACT(profile, '$.last_name') IS NOT NULL AND
    LENGTH(JSON_UNQUOTE(JSON_EXTRACT(profile, '$.first_name'))) >= 1 AND
    LENGTH(JSON_UNQUOTE(JSON_EXTRACT(profile, '$.last_name'))) >= 1
  ),

  -- Complex nested preferences with validation
  preferences JSONB CHECK (
    JSON_VALID(preferences) AND
    JSON_EXTRACT(preferences, '$.notifications.email.frequency') IN ('immediate', 'daily', 'weekly', 'never') AND
    JSON_EXTRACT(preferences, '$.privacy.profile_visibility') IN ('public', 'friends', 'private') AND
    JSON_EXTRACT(preferences, '$.interface.theme') IN ('light', 'dark', 'auto')
  ),

  -- Account information with business logic validation
  account JSONB NOT NULL CHECK (
    JSON_VALID(account) AND
    JSON_EXTRACT(account, '$.status') IN ('active', 'inactive', 'suspended', 'pending') AND
    JSON_EXTRACT(account, '$.type') IN ('free', 'premium', 'enterprise', 'admin') AND
    (
      JSON_EXTRACT(account, '$.type') != 'premium' OR 
      JSON_EXTRACT(account, '$.subscription_expires_at') IS NOT NULL
    )
  ),

  -- Audit timestamps with constraints
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  deleted_at TIMESTAMP NULL,

  -- Complex business logic constraints
  CONSTRAINT valid_birth_date CHECK (
    JSON_EXTRACT(profile, '$.birth_date') IS NULL OR
    JSON_EXTRACT(profile, '$.birth_date') <= CURRENT_DATE
  ),

  CONSTRAINT profile_completeness CHECK (
    (JSON_EXTRACT(account, '$.type') != 'premium') OR
    (
      JSON_EXTRACT(profile, '$.phone_number') IS NOT NULL AND
      JSON_EXTRACT(profile, '$.bio') IS NOT NULL
    )
  ),

  -- Conditional validation based on account type
  CONSTRAINT admin_verification CHECK (
    (JSON_EXTRACT(account, '$.type') != 'admin') OR
    (JSON_EXTRACT(account, '$.verification.identity_verified') = true)
  )
) WITH (
  validation_level = 'strict',
  validation_action = 'error'
);

-- Insert data with comprehensive validation
INSERT INTO users (
  email, username, password_hash, profile, preferences, account
) VALUES (
  '[email protected]',
  'johndoe123', 
  '$2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewdBxJzybKlJNcX.',
  JSON_OBJECT(
    'first_name', 'John',
    'last_name', 'Doe',
    'birth_date', '1990-05-15',
    'phone_number', '+1-555-123-4567',
    'bio', 'Software engineer passionate about technology',
    'social_links', JSON_OBJECT(
      'twitter', '@johndoe',
      'github', 'johndoe',
      'linkedin', 'john-doe-dev'
    )
  ),
  JSON_OBJECT(
    'notifications', JSON_OBJECT(
      'email', JSON_OBJECT(
        'marketing', false,
        'security', true,
        'frequency', 'daily'
      ),
      'push', JSON_OBJECT(
        'enabled', true,
        'frequency', 'immediate'
      )
    ),
    'privacy', JSON_OBJECT(
      'profile_visibility', 'friends',
      'search_visibility', true
    ),
    'interface', JSON_OBJECT(
      'theme', 'dark',
      'language', 'en-US',
      'timezone', 'America/New_York'
    )
  ),
  JSON_OBJECT(
    'status', 'active',
    'type', 'free',
    'verification', JSON_OBJECT(
      'email_verified', false,
      'verification_level', 'none'
    ),
    'security', JSON_OBJECT(
      'two_factor_enabled', false,
      'failed_login_attempts', 0
    )
  )
);

-- Advanced validation queries and data quality checks
WITH validation_analysis AS (
  SELECT 
    _id,
    email,
    username,

    -- Profile completeness scoring
    CASE 
      WHEN JSON_EXTRACT(profile, '$.bio') IS NOT NULL 
           AND JSON_EXTRACT(profile, '$.phone_number') IS NOT NULL
           AND JSON_EXTRACT(profile, '$.social_links') IS NOT NULL THEN 100
      WHEN JSON_EXTRACT(profile, '$.bio') IS NOT NULL 
           OR JSON_EXTRACT(profile, '$.phone_number') IS NOT NULL THEN 70
      WHEN JSON_EXTRACT(profile, '$.first_name') IS NOT NULL 
           AND JSON_EXTRACT(profile, '$.last_name') IS NOT NULL THEN 40
      ELSE 20
    END as profile_completeness_score,

    -- Preference configuration analysis
    CASE 
      WHEN JSON_EXTRACT(preferences, '$.notifications') IS NOT NULL
           AND JSON_EXTRACT(preferences, '$.privacy') IS NOT NULL
           AND JSON_EXTRACT(preferences, '$.interface') IS NOT NULL THEN 'complete'
      WHEN JSON_EXTRACT(preferences, '$.notifications') IS NOT NULL THEN 'partial'
      ELSE 'minimal'
    END as preferences_status,

    -- Account validation status
    JSON_EXTRACT(account, '$.status') as account_status,
    JSON_EXTRACT(account, '$.type') as account_type,
    JSON_EXTRACT(account, '$.verification.verification_level') as verification_level,

    -- Data quality flags
    JSON_VALID(profile) as profile_valid,
    JSON_VALID(preferences) as preferences_valid,
    JSON_VALID(account) as account_valid,

    -- Business rule compliance
    CASE 
      WHEN JSON_EXTRACT(account, '$.type') = 'premium' 
           AND JSON_EXTRACT(account, '$.subscription_expires_at') IS NULL THEN false
      ELSE true
    END as subscription_rule_compliant,

    created_at,
    updated_at

  FROM users
  WHERE deleted_at IS NULL
),

data_quality_report AS (
  SELECT 
    COUNT(*) as total_users,

    -- Profile quality metrics
    AVG(profile_completeness_score) as avg_profile_completeness,
    COUNT(*) FILTER (WHERE profile_completeness_score >= 80) as high_quality_profiles,
    COUNT(*) FILTER (WHERE profile_completeness_score < 50) as low_quality_profiles,

    -- Validation compliance
    COUNT(*) FILTER (WHERE profile_valid = false) as invalid_profiles,
    COUNT(*) FILTER (WHERE preferences_valid = false) as invalid_preferences,
    COUNT(*) FILTER (WHERE account_valid = false) as invalid_accounts,

    -- Business rule compliance
    COUNT(*) FILTER (WHERE subscription_rule_compliant = false) as subscription_violations,

    -- Account distribution
    COUNT(*) FILTER (WHERE account_type = 'free') as free_accounts,
    COUNT(*) FILTER (WHERE account_type = 'premium') as premium_accounts,
    COUNT(*) FILTER (WHERE account_type = 'enterprise') as enterprise_accounts,

    -- Verification status
    COUNT(*) FILTER (WHERE verification_level = 'none') as unverified_users,
    COUNT(*) FILTER (WHERE verification_level IN ('email', 'phone', 'identity', 'full')) as verified_users,

    -- Recent activity
    COUNT(*) FILTER (WHERE created_at >= CURRENT_DATE - INTERVAL '30 days') as new_users_30d,
    COUNT(*) FILTER (WHERE updated_at >= CURRENT_DATE - INTERVAL '7 days') as active_users_7d

  FROM validation_analysis
)

SELECT 
  total_users,
  ROUND(avg_profile_completeness, 1) as avg_profile_quality,
  ROUND((high_quality_profiles / total_users::float * 100), 1) as high_quality_pct,
  ROUND((low_quality_profiles / total_users::float * 100), 1) as low_quality_pct,

  -- Data integrity summary
  CASE 
    WHEN (invalid_profiles + invalid_preferences + invalid_accounts) = 0 THEN 'excellent'
    WHEN (invalid_profiles + invalid_preferences + invalid_accounts) < total_users * 0.01 THEN 'good'
    WHEN (invalid_profiles + invalid_preferences + invalid_accounts) < total_users * 0.05 THEN 'acceptable'
    ELSE 'poor'
  END as data_integrity_status,

  -- Business rule compliance
  CASE 
    WHEN subscription_violations = 0 THEN 'compliant'
    WHEN subscription_violations < total_users * 0.01 THEN 'minor_issues'
    ELSE 'major_violations'
  END as business_rule_compliance,

  -- Account distribution summary
  JSON_OBJECT(
    'free', free_accounts,
    'premium', premium_accounts, 
    'enterprise', enterprise_accounts
  ) as account_distribution,

  -- Verification summary
  ROUND((verified_users / total_users::float * 100), 1) as verification_rate_pct,

  -- Growth metrics
  new_users_30d,
  active_users_7d,

  -- Recommendations
  CASE 
    WHEN low_quality_profiles > total_users * 0.3 THEN 'Focus on profile completion campaigns'
    WHEN unverified_users > total_users * 0.5 THEN 'Improve verification processes'
    WHEN subscription_violations > 0 THEN 'Review premium account management'
    ELSE 'Data quality is good'
  END as primary_recommendation

FROM data_quality_report;

-- Schema evolution with validation migration
-- Add new validation rules with backward compatibility
ALTER TABLE users 
ADD CONSTRAINT enhanced_email_validation CHECK (
  email REGEXP '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$' AND
  email NOT LIKE '%@example.com' AND
  email NOT LIKE '%@test.%' AND
  LENGTH(email) >= 5 AND
  LENGTH(email) <= 254
);

-- Modify existing constraints with migration support
ALTER TABLE users 
MODIFY CONSTRAINT profile_completeness CHECK (
  (JSON_EXTRACT(account, '$.type') NOT IN ('premium', 'enterprise')) OR
  (
    JSON_EXTRACT(profile, '$.phone_number') IS NOT NULL AND
    JSON_EXTRACT(profile, '$.bio') IS NOT NULL AND
    JSON_EXTRACT(profile, '$.social_links') IS NOT NULL
  )
);

-- Add conditional validation based on account age
ALTER TABLE users
ADD CONSTRAINT mature_account_validation CHECK (
  (DATEDIFF(CURRENT_DATE, created_at) < 30) OR
  (
    JSON_EXTRACT(account, '$.verification.email_verified') = true AND
    profile_completeness_score >= 60
  )
);

-- Create validation monitoring view
CREATE VIEW user_validation_status AS
SELECT 
  _id,
  email,
  username,
  JSON_EXTRACT(account, '$.status') as status,
  JSON_EXTRACT(account, '$.type') as type,

  -- Validation status flags
  JSON_VALID(profile) as profile_structure_valid,
  JSON_VALID(preferences) as preferences_structure_valid,
  JSON_VALID(account) as account_structure_valid,

  -- Business rule compliance checks
  (
    JSON_EXTRACT(account, '$.type') != 'premium' OR 
    JSON_EXTRACT(account, '$.subscription_expires_at') IS NOT NULL
  ) as subscription_valid,

  (
    JSON_EXTRACT(account, '$.type') != 'admin' OR
    JSON_EXTRACT(account, '$.verification.identity_verified') = true
  ) as admin_verification_valid,

  -- Data completeness assessment  
  CASE 
    WHEN JSON_EXTRACT(profile, '$.first_name') IS NULL THEN 'missing_required_profile_data'
    WHEN JSON_EXTRACT(profile, '$.phone_number') IS NULL 
         AND JSON_EXTRACT(account, '$.type') IN ('premium', 'enterprise') THEN 'incomplete_premium_profile'
    WHEN email NOT REGEXP '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$' THEN 'invalid_email_format'
    ELSE 'valid'
  END as validation_status,

  created_at,
  updated_at

FROM users
WHERE deleted_at IS NULL;

-- QueryLeaf provides comprehensive document validation capabilities:
-- 1. SQL-familiar constraint syntax with CHECK clauses and business logic
-- 2. JSON validation functions for nested object and array validation  
-- 3. Conditional validation based on field values and account types
-- 4. Complex business rule enforcement through constraint expressions
-- 5. Schema evolution support with backward compatibility options
-- 6. Data quality monitoring and validation status reporting
-- 7. Integration with MongoDB's native document validation features
-- 8. Familiar SQL patterns for constraint management and modification
-- 9. Real-time validation feedback and error handling
-- 10. Comprehensive validation reporting and compliance tracking

Best Practices for Document Validation Implementation

Validation Strategy Design

Essential principles for effective MongoDB document validation:

  1. Progressive Validation: Start with loose validation and progressively tighten rules as data quality improves
  2. Business Rule Integration: Embed business logic directly into validation rules for consistency
  3. Schema Versioning: Implement versioning strategies for smooth schema evolution
  4. Performance Consideration: Balance validation thoroughness with insertion performance
  5. Error Handling: Design clear, actionable error messages for validation failures
  6. Testing Strategy: Thoroughly test validation rules with edge cases and invalid data

Production Implementation

Optimize MongoDB document validation for production environments:

  1. Validation Levels: Use appropriate validation levels (strict, moderate, off) for different environments
  2. Migration Planning: Plan validation changes with proper testing and rollback strategies
  3. Performance Monitoring: Monitor validation impact on write performance and throughput
  4. Data Quality Tracking: Implement comprehensive data quality monitoring and alerting
  5. Documentation: Maintain clear documentation of validation rules and business logic
  6. Compliance Integration: Align validation rules with regulatory and compliance requirements

Conclusion

MongoDB Document Validation provides the perfect balance between schema flexibility and data integrity, enabling applications to evolve rapidly while maintaining data quality and consistency. The powerful validation system supports complex business logic, nested object validation, and gradual schema evolution without the rigid constraints and expensive migrations of traditional relational systems.

Key MongoDB Document Validation benefits include:

  • Flexible Schema Evolution: Modify validation rules without downtime or complex migrations
  • Rich Validation Logic: Support for complex business rules, nested objects, and conditional constraints
  • JSON Schema Standard: Industry-standard validation with MongoDB-specific enhancements
  • Performance Integration: Validation optimizations that work with MongoDB's document architecture
  • Development Agility: Real-time validation feedback that accelerates development cycles
  • Data Quality Assurance: Comprehensive validation reporting and quality monitoring capabilities

Whether you're building user management systems, e-commerce platforms, content management applications, or any system requiring reliable data integrity with flexible schema design, MongoDB Document Validation with QueryLeaf's familiar SQL interface provides the foundation for robust, maintainable data validation.

QueryLeaf Integration: QueryLeaf automatically handles MongoDB document validation while providing SQL-familiar constraint syntax, validation functions, and schema management operations. Complex validation rules, business logic constraints, and data quality monitoring are seamlessly managed through familiar SQL constructs, making sophisticated document validation both powerful and accessible to SQL-oriented development teams.

The combination of flexible document validation with SQL-style operations makes MongoDB an ideal platform for applications requiring both rigorous data integrity and rapid schema evolution, ensuring your applications can adapt to changing requirements while maintaining the highest standards of data quality and consistency.