0

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
1

1 Answer 1

1
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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.