Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Calculating Sums with MongoDB Aggregation

Tech 2

To compute the sum of a field in MongoDB, use the aggregation frameowrk. This process involves connecting to the database, defining a data model, and executing an aggregation pipeline.

First, establish a connection to MongoDB using a Node.js driver like Mongoose. Ensure MongoDB is installed and running locally.

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/testdb', {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

Next, define a schema for the collection. For example, if you have a collection named 'employees' with a 'salary' field, create a model as follows:

const employeeSchema = new mongoose.Schema({
    salary: Number
});
const Employee = mongoose.model('Employee', employeeSchema);

To calculate the total salary, use the aggregate method with a $group stage. The $sum operator accumulates values from the specified field.

Employee.aggregate([
    {
        $group: {
            _id: null,
            totalSalary: { $sum: '$salary' }
        }
    }
]).then(result => {
    console.log('Sum result:', result);
}).catch(error => {
    console.error('Error during aggregation:', error);
});

In this code, the $group stage groups all documants (using _id: null to treat them as a single group) and computes the sum of the 'salary' field, storing it in 'totalSalary'. The result is an array containing an object with the total.

Run the script in a Node.js environment to execute the query. The output will display the calculated sum, such as [{ _id: null, totalSalary: 50000 }].

Tags: MongoDB

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.