5

I have a document related to the role or designations of employees. This is the document structure.

{
    "_id" : ObjectId("5660c2a5b6fcba2d47baa2d9"),
    "role_id" : 4,
    "role_title" : "Carpenter",
    "employees" : [ 
        {
            "$ref" : "employees",
            "$id" : 4,
            "$db" : "db_cw2"
        }, 
        {
            "$ref" : "employees",
            "$id" : 5,
            "$db" : "db_cw2"
        }
    ]
},

{
    "_id" : ObjectId("5660c2a5b6fcba2d47baa2d6"),
    "role_id" : 1,
    "role_title" : "Chief Executive",
    "employees" : [ 
        {
            "$ref" : "employees",
            "$id" : 1,
            "$db" : "db_cw2"
        }
    ]
}

I want to write a query to show or count total number of employees who are working as 'Carpenter' or simple words count number of elements in 'employees' field where 'role_title' : 'Carpenter'.

I have written this query but it shows total number of employees in all the documents of the collection.

db.employee_role.aggregate(
   {
        $project: { 
            count: { $size:"$employees" }
        }
   }
)
1
  • use $match in aggregation like this {"$match":{"role_title" : "Carpenter"}} and then project Commented Dec 14, 2015 at 13:34

2 Answers 2

7

You have to use $group instead:

db.employee_role.aggregate(
   {
        $group: {
            _id: "$role_title",
            total: { $sum: { $size:"$employees" } }
        }
   }
)

You group by role_title and then, you add the number of employees.

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

Comments

3

You could use this:

db.employee_role.aggregate(
  [
    {
      $match: { role_title: "Carpenter" }
    },
    {
      $group: {
        _id: "$role_title",
        total: { $sum: { $size: "$employees"} }
      }
    }
  ]
)

Comments

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.