DEV Community

Anjali Gurjar
Anjali Gurjar

Posted on

Mongoose query

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();

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more