1

I have two collections in my MongoDB employee and employeeData i need to get some statics information from DB.

  1. total employees who were not deleted.
  2. total employees who have security access and are not deleted.
  3. total employees still active;

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

1 Answer 1

1
  • $match to check isDeleted condition
  • $lookup with EmployeeData
  • $group by null
    • get total employees count,
    • count total security access if securityAccess is true
    • count total active employees if isActive 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
          ]
        }
      }
    }
  }
])

Playground

Sign up to request clarification or add additional context in comments.

1 Comment

@turvishal i made one mistake here in my EmployeeData isActive is a string not boolean.its either active or inActive. i change the query like this $cond: [{ isActive:['$eq','Active']}, 1, 0] but it didn't work.update my question sorry for the inconvenience.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.