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() {
c…


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


Print Share Comment Cite Upload Translate Updates
APA

Anjali Gurjar | Sciencx (2025-01-07T10:48:11+00:00) Mongoose query. Retrieved from https://www.scien.cx/2025/01/07/mongoose-query/

MLA
" » Mongoose query." Anjali Gurjar | Sciencx - Tuesday January 7, 2025, https://www.scien.cx/2025/01/07/mongoose-query/
HARVARD
Anjali Gurjar | Sciencx Tuesday January 7, 2025 » Mongoose query., viewed ,<https://www.scien.cx/2025/01/07/mongoose-query/>
VANCOUVER
Anjali Gurjar | Sciencx - » Mongoose query. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/01/07/mongoose-query/
CHICAGO
" » Mongoose query." Anjali Gurjar | Sciencx - Accessed . https://www.scien.cx/2025/01/07/mongoose-query/
IEEE
" » Mongoose query." Anjali Gurjar | Sciencx [Online]. Available: https://www.scien.cx/2025/01/07/mongoose-query/. [Accessed: ]
rf:citation
» Mongoose query | Anjali Gurjar | Sciencx | 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.

You must be logged in to translate posts. Please log in or register.