ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

MongoDB Aggregation Pipeline for Grouping and Summing

MongoDB Query Language

Goal -- WPM

Ready
Exercise Algorithm Area
1function aggregateSalesData(collection, groupField, sumField) {
2// Validate input parameters
3if (!collection || typeof collection !== 'object') {
4throw new Error('Invalid collection provided.');
5}
6if (typeof groupField !== 'string' || groupField.length === 0) {
7throw new Error('Invalid groupField provided.');
8}
9if (typeof sumField !== 'string' || sumField.length === 0) {
10throw new Error('Invalid sumField provided.');
11}
12
13// Construct the aggregation pipeline
14// This pipeline groups documents by a specified field and calculates the sum
15// of another field for each group.
16const pipeline = [
17// Stage 1: Group documents by the 'groupField' and sum the 'sumField'
18{
19'$group': {
20'_id': '$' + groupField, // Group by the value of groupField
21'totalAmount': { '$sum': '$' + sumField } // Sum the values of sumField
22}
23},
24// Stage 2: Sort the results by the total amount in descending order
25{
26'$sort': {
27'totalAmount': -1
28}
29},
30// Stage 3: Project the output to a more readable format (optional)
31{
32'$project': {
33'_id': 0, // Exclude the default _id field
34'category': '$_id', // Rename _id to 'category'
35'totalSales': '$totalAmount' // Rename totalAmount to 'totalSales'
36}
37}
38];
39
40// Execute the aggregation pipeline
41// In a real application, this would involve a database driver.
42// For this example, we simulate the pipeline execution.
43console.log('Executing aggregation pipeline:', JSON.stringify(pipeline));
44// return collection.aggregate(pipeline).toArray(); // Example of actual DB call
45return []; // Placeholder for simulation
46}
47
48// Helper function to simulate a collection with aggregation capabilities
49function simulateAggregatableCollection() {
50return {
51aggregate: function(pipeline) {
52console.log('Simulating aggregation with pipeline:', pipeline);
53return {
54toArray: function() {
55console.log('Simulating toArray call for aggregation.');
56// Simulate results based on a hypothetical dataset for sales
57if (pipeline && pipeline.length > 0 && pipeline[0].$group && pipeline[0].$group._id === '$category') {
58return [
59{ category: 'Electronics', totalSales: 15000 },
60{ category: 'Clothing', totalSales: 8000 },
61{ category: 'Home Goods', totalSales: 12000 }
62];
63}
64return [];
65}
66};
67}
68};
69}
70
71// Example Usage:
72// const salesCollection = simulateAggregatableCollection();
73// const aggregatedResults = aggregateSalesData(salesCollection, 'category', 'price');
74// console.log('Aggregated Results:', aggregatedResults);
Algorithm description viewbox

MongoDB Aggregation Pipeline for Grouping and Summing

Algorithm description:

This function demonstrates a MongoDB aggregation pipeline to group documents by a specified field and calculate the sum of another field for each group. It's commonly used for generating reports, summarizing data, and performing complex data transformations. For instance, it can be used to calculate total sales per product category or the total number of orders per customer. The pipeline includes stages for grouping, sorting, and projecting the results into a user-friendly format.

Algorithm explanation:

The `aggregateSalesData` function builds and executes a MongoDB aggregation pipeline. The pipeline starts with a `$group` stage, which uses the `_id` field to define the grouping key (e.g., 'category') and the `$sum` accumulator to compute the total of a specified field (e.g., 'price') for each group. Following the `$group` stage, a `$sort` stage orders the results, typically by the aggregated sum in descending order to show top performers. Finally, a `$project` stage reshapes the output documents, renaming fields for clarity and excluding unnecessary ones. Input validation ensures that the collection and field names are valid. The time complexity of aggregation pipelines can vary greatly depending on the stages and data size, but for simple grouping and summing, it's often proportional to the number of documents processed. Indexing the `groupField` can significantly optimize the `$group` stage. Space complexity is determined by the intermediate data generated during the pipeline execution and the final output size.

Pseudocode:

function aggregateSalesData(collection, groupField, sumField):
  validate collection, groupField, sumField
  create aggregation pipeline:
    stage 1: group by groupField, sum sumField into totalAmount
    stage 2: sort by totalAmount descending
    stage 3: project to category and totalSales
  execute pipeline on collection
  return results