计算MongoDB中的元素数量

时间:2018-01-09 07:14:06

标签: mongodb count elements

我想获得MongoDB集合中元素的总数。

在来自JSON集合的示例MongoDB中,我需要计算MongoDB个集合中所有批次中任务下的元素数量,

{
    "_id": "PROJECTNAME",
    "path": "/PROJECTPATH/PROJECTNAME",
    "batches": {
        "Batch01": {
            "tasks": {
                "SHOT_ZBR_sh0060": {
                    "key": "value"
                },
                "ZBR_sh0100": {
                    "key": "value"
                }
            },
            "name": "Batch01"
        },
        "Batch02": {
            "tasks": {
                "SHOT_ZMI_sh0080": {
                    "key": "value"
                },
                "SHOT_ZMI_sh0030_combined": {
                    "key": "value"
                },
                "SHOT_ZMI_sh0010": {
                    "key": "value"
                }
            },
            "name": "Batch02"
        },
        "Batch03": {
            "tasks": {
                "SHOT_ZMI_sh0130": {
                    "key": "value"
                }
            },
            "name": "Batch03"
        }
    },
    "name": "PROJECTNAME"
}

1 个答案:

答案 0 :(得分:1)

最好将任务和批次定义为数组,以便使用count轻松计算。否则通过简单的JavaScript来计算

//let obj = your object
tasksCount=0
Object.keys(obj.batches).forEach(v=>{
    tasksCount+=Object.keys(obj.batches[v].tasks).length
})
console.log(tasksCount)