Reputation: 1780
I have two collections in my MongoDB employee
and employeeData
i need to get some statics information from DB.
this is my Employee
collection sample document
{
_id:'5ec25e74d028af28343f1061'
isDeleted:false
securityAccess:true
details:'60475b7a93ac45d64a5957b0'
}
this is EmployeeData
collection document
{
_id:'60475b7a93ac45d64a5957b0'
emplyeeId:'5ec25e74d028af28343f1061'
isActive:'active',
salary:225543.00,
department:'sales'
}
I need to get this data from one query using some kind of aggregations but I'm not much familiar with the MongoDB queries.
the expected result looks like this.
Total Employees | Active Employees | Security Access
10 5 2
Upvotes: 1
Views: 396
Reputation: 36144
$match
to check isDeleted
condition$lookup
with EmployeeData
$group
by null
securityAccess
is trueisActive
is 'active'db.Employee.aggregate([
{ $match: { isDeleted: false } },
{
$lookup: {
from: "EmployeeData",
localField: "_id",
foreignField: "emplyeeId",
as: "activeEmployees"
}
},
{
$group: {
_id: null,
totalEmployees: { $sum: 1 },
securityAccess: {
$sum: {
$cond: ["$securityAccess", 1, 0]
}
},
activeEmployees: {
$sum: {
$cond: [
{ $eq: [{ $first: "$activeEmployees.isActive" }, "active"] },
1,
0
]
}
}
}
}
])
Upvotes: 1