0

I want to get the total count of elements in a MongoDB collection.

In the sample JSON from MongoDB collection, I need to take count of elements under tasks in all the batches throughout the MongoDB collections,

{
    "_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"
}
ArifMustafa
  • 4,617
  • 5
  • 40
  • 48
Aditya
  • 1
  • 4
  • Do you assume that there will be only Batch01...03 or is it dynamic ? – mickl Jan 09 '18 at 07:17
  • get a help from https://docs.mongodb.com/manual/reference/method/db.collection.count/ and https://stackoverflow.com/questions/21387969/mongodb-count-the-number-of-items-in-an-array and possibly your question is duplicate of last one. – ArifMustafa Jan 09 '18 at 07:21
  • There can be more than that . – Aditya Jan 09 '18 at 07:26

1 Answers1

1

better to define tasks and batches as array to easy calculate using count. otherwise go throught plain javascript to count

//let obj = your object
tasksCount=0
Object.keys(obj.batches).forEach(v=>{
    tasksCount+=Object.keys(obj.batches[v].tasks).length
})
console.log(tasksCount)
shivshankar
  • 2,067
  • 1
  • 18
  • 28