计算文档中数组内的元素总数 - MongoDB [英] count total number of elements inside an array in document - MongoDB

查看:9
本文介绍了计算文档中数组内的元素总数 - MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一份与员工角色或职务相关的文件.这是文档结构.

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" }
        }
   }
)

推荐答案

你必须使用 $group 代替:

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

您按 role_title 分组,然后添加员工人数.

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

这篇关于计算文档中数组内的元素总数 - MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆