Count total number of elements inside an array in a document - MongoDB

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

{
    "_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 the total number of employees who work as "Carpenter", or simple words count the number of elements in the "employees" field, where "role_title": "Carpenter".

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

db.employee_role.aggregate(
   {
        $project: { 
            count: { $size:"$employees" }
        }
   }
)
+4
source share
2 answers

Instead, you should use $group:

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

You group role_titleand then add the number of employees.

+2

:

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

Source: https://habr.com/ru/post/1619888/


All Articles