count total number of elements inside an array in document - MongoDB

前端 未结 2 684
遥遥无期
遥遥无期 2021-01-03 08:07

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

{
    \"_id\" : ObjectId(\"5660c2a5b6fcba2d47baa2d9\"),
          


        
2条回答
  •  走了就别回头了
    2021-01-03 08:33

    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.

提交回复
热议问题