This content originally appeared on DEV Community and was authored by Anjali Gurjar
const mongoose = require('mongoose');
const Employee = require('./Employee'); // Assuming the Employee model exists
const Department = require('./Department'); // Assuming the Department model exists
async function getEmployeeCountByDepartment() {
const result = await Employee.aggregate([
{
$lookup: {
from: 'departments', // This is the collection name in MongoDB
localField: 'department', // The field in Employee model that holds department reference
foreignField: '_id', // The field in Department model that we are referencing
as: 'department_info', // The resulting array will be called department_info
}
},
{
$unwind: '$department_info' // Unwind the department_info array to flatten the structure
},
{
$group: {
_id: '$department_info.name', // Group by department name
employee_count: { $sum: 1 } // Count the number of employees in each department
}
},
{
$sort: { employee_count: -1 } // Optionally, sort by employee count in descending order
}
]);
console.log(result); // This will print the department and its corresponding employee count
}
getEmployeeCountByDepartment();
This content originally appeared on DEV Community and was authored by Anjali Gurjar

Anjali Gurjar | Sciencx (2025-01-07T10:48:11+00:00) Mongoose query. Retrieved from https://www.scien.cx/2025/01/07/mongoose-query/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.