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

前端 未结 2 685
遥遥无期
遥遥无期 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.

    0 讨论(0)
  • 2021-01-03 08:36

    You could use this:

    db.employee_role.aggregate(
      [
        {
          $match: { role_title: "Carpenter" }
        },
        {
          $group: {
            _id: "$role_title",
            total: { $sum: { $size: "$employees"} }
          }
        }
      ]
    )
    
    0 讨论(0)
提交回复
热议问题