2017-02-13 28 views
2

我有公司,像這樣的集合MongoDB數據庫(它只是一個樣本,實際收集大得多):

[ 
    { 
    "_id": 100, 
    "name": "Test Name 1", 
    "level": "1" 
    }, 
    { 
    "_id": 101, 
    "name": "Test Name 2", 
    "level": "1" 
    }, 
    { 
    "_id": 102, 
    "name": "Test Name 3", 
    "level": "2" 
    } 
] 

其中,「水平」只能介於0到5

我試圖用$ group和$ project來計算一個聚合查詢,它計算每個級別有多少公司,但根據我需要遵循的API規範,它需要像這樣格式化爲單個對象:

{ 
    "metrics": { 
    "companies": { 
     "total": <integer>, 
     "level1": <integer>, 
     "level2": <integer>, 
     "level3": <integer>, 
     "level4": <integer>, 
     "level5": <integer> 
    } 
    } 
} 

我能得到這個使用$組和$項目這樣的最接近:

Companies.aggregate([{ 
      $group: { 
       _id: { 
        level: "$level" 
       }, 
       count: { 
        $sum: 1 
       } 
      } 
     }, 
     { 
      $project: { 
       _id: 0, 
       level: "$_id.level", 
       total: "$count" 
      } 
     } 
    ]) 

其中給出以下結果:

[ 
    { 
    "level": 3, 
    "total": 108 
    }, 
    { 
    "level": 5, 
    "total": 172 
    }, 
    { 
    "level": 2, 
    "total": 624 
    }, 
    { 
    "level": 4, 
    "total": 98 
    }, 
    { 
    "level": 1, 
    "total": 137 
    }, 
    { 
    "level": 0, 
    "total": 94 
    } 
] 

然而,這樣的結果是一個數組,我需要把根據規範,新密鑰「level1」,「level2」等的單個對象中每個級別的數據。

我相信我需要做另一個$組操作,但我無法找到如何去做。

任何想法?

回答

0

我不知道如果我理解,但我想你只需要映射它,就像這裏:

> var aux = new Object; 
> db.Companies.aggregate([ 
    { 
    $group: { 
     _id: { 
     level: "$level" 
     }, 
     count: { 
     $sum: 1 
     } 
    } 
    }, 
    { 
    $project: { 
     _id: 0, 
     level: "$_id.level", 
     total: "$count" 
    } 
    } 
]).forEach(function(a){aux["level"+a.level] = a.total;}); 
> printjson(aux); 
{ "level2" : 1, "level1" : 2 } 
+0

實際上,我是希望我能直接從彙總查詢得到它,而不需要一個for循環,但這提供了很好的解決方案。謝謝! –

0

我相信有可能是更好的解決方案,但這個工作:

db.companies.aggregate([{ 
$group:{_id:{level: "$level"}, count: {$sum: 1}}}, 
{$group:{"_id": 0, levels: {$push: {_id:"$_id.level", count: "$count"}}, total: {$sum: "$count"}}}, 
{$unwind: "$levels"}, 
{$sort: {"levels._id": 1}}, 
{$group:{_id: 0, levels: {$push: {levels:"$levels.count"}}, "total": {$avg:"$total"}}}, 
{$project: {total: "$total", level1: {$arrayElemAt: ["$levels",0]}, level2: {$arrayElemAt: ["$levels", 1]}, level3: {$arrayElemAt: ["$levels",2]}, level4: {$arrayElemAt: ["$levels",3]},level5: {$arrayElemAt: ["$levels",4]} }}, 
{$project: {_id: 0, metrics: {companies: {total: "$total", level1: "$level1.levels", level2: "$level2.levels", level3: "$level3.levels",level4: "$level4.levels", level5: "$level5.levels"}}}} 
]) 

返回的結果:

{ "metrics" : 
{ "companies" : 
    { "total" : 7, 
    "level1" : 1, 
    "level2" : 2, 
    "level3" : 2, 
    "level4" : 1, 
    "level5" : 1 
} } } 
相關問題