chou
chou

Reputation: 263

count many different values with mongoDB

Here is a clear example of documents

{
    "_id" : ObjectId("56d8559b634049654854f621"),
    "nameFile" : "FDR-IA 444",
    "type" : "type",
    "branch" : "branch",
    "service" : "service",
    "bin" : { "$binary" : 'binary code of the file'}
},
{
    "_id" : ObjectId("56d8559b634049654854f622"),
    "nameFile" : "FDR-IA",
    "type" : "type",
    "branch" : "branch1",
    "service" : "service",
    "bin" : { "$binary" : 'binary code of the file'}
},
{
    "_id" : ObjectId("56d8559b634049654854f623"),
    "nameFile" : "FDR",
    "type" : "type1",
    "branch" : "branch2",
    "service" : "service",
    "bin" : { "$binary" : 'binary code of the file'}
},
{
    "_id" : ObjectId("56d8559b634049654854f624"),
    "nameFile" : "FDR -test",
    "type" : "type1",
    "branch" : "branch2",
    "service" : "service",
    "bin" : { "$binary" : 'binary code of the file'}
}

My mongoDB contains documents with this format and I want to count all the services, all the branchs for each service, all the types for each service, all the files for each service.

A file belongs to a unique type, a type belongs to a unique branch, and a branch belongs to a unique service: that's my conception.

To count each value, I know that I should make many mongo requests with callbacks, I want to optimize my code, I tried to use bulk but it doesn't have the count option.

For the given example: I want this result :

   name of service     numbBranchs    numbTypes     numbFiles
     'service'             3              2             4

Upvotes: 0

Views: 55

Answers (1)

Hiren S.
Hiren S.

Reputation: 2832

db.getCollection('services').aggregate([
    {
        "$group": {
            "_id": "$service",
            "files": {
                "$sum": 1
            },
            "branches": {
                "$addToSet": "$branch"
            },
            "types": {
                "$addToSet": "$type"
            }
        }
    }, {
        "$project": {
            "name of service ": "$_id",
            "numbFiles": "$files",
            "numbBranches": {
                "$size": "$branches"
            },
            "numbTypes": {
                "$size": "$types"
            }
        }
    }

]);

MongoDB output:

{
    "waitedMS" : NumberLong(0),
    "result" : [ 
        {
            "_id" : "service",
            "name of service " : "service",
            "numbFiles" : 4,
            "numbBranchs" : 3,
            "numbTypes" : 2
        }
    ],
    "ok" : 1.0000000000000000
}

Upvotes: 1

Related Questions