使用mongoDB计算许多不同的值

时间:2016-05-17 10:40:39

标签: node.js mongodb mongodb-query aggregation-framework

这是文件的一个明显例子

{
    "_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'}
}

我的mongoDB包含具有此格式的文档,我想计算所有服务,每个服务的所有分支,每个服务的所有类型,每个服务的所有文件。

文件属于唯一类型,类型属于唯一分支,分支属于唯一服务:这是我的概念。

要计算每个值,我知道我应该使用回调制作许多mongo请求,我想优化我的代码,我尝试使用批量但是它没有计数选项。

对于给定的例子:我想要这个结果:

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

1 个答案:

答案 0 :(得分: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输出:

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