Blog>
Snippets

Aggregation Pipeline for Summarizing Data

Use MongoDB's aggregation framework to summarize RAG status reports, calculating averages and counts of items in each category.

// HTML structure
<div id="rag-summary"></div>
A div element in the HTML is designated as a container for displaying the summary.

/* CSS styles */
#rag-summary {
    margin: 20px;
    padding: 10px;
    background-color: #f5f5f5;
    border: 1px solid #ddd;
}
CSS provides basic styling for the RAG summary container.

// Javascript: MongoDB Aggregation Pipeline

async function summarizeRAGStatus(db) {
    const pipeline = [
        {
            $group: {
                _id: '$status',
                averageScore: { $avg: '$score' },
                count: { $sum: 1 }
            }
        }
    ];

    try {
        const result = await db.collection('rag_reports').aggregate(pipeline).toArray();
        displaySummary(result);
    } catch (error) {
        console.error('Error in aggregation pipeline:', error);
    }
}

function displaySummary(data) {
    const summaryElement = document.getElementById('rag-summary');
    summaryElement.innerHTML = data.map(item => `<p>Status: ${item._id}<br>Average Score: ${item.averageScore.toFixed(2)}<br>Count: ${item.count}</p>`).join('');
}
JavaScript connects to MongoDB and runs an aggregation pipeline to process the RAG status reports collection, calculates averages and counts, and outputs the result into the HTML container.