我想获得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"
}
答案 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)