Calculating Sums with MongoDB Aggregation
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 }].