2017-10-09 35 views
0

我想實現下面的查詢儘可能高效所以我使用MongoDB的Aggregation框架屬性。MongoDB的碎石集團而獲得伯爵哪個平等條件

我有一個名爲mydevices集合包含各自表示下面的格式的設備文件:

{ 
    BUILDING: 'stringValue', 
    DEVICECLASS: 'stringValue', 
} 

其中我想要實現的輸出是針對每個BUILDING含有每設備的計數陣列每個類別中的DEVICECLASS例如

'building xy': { 
    'mobile phone': 5, 
    'destkop': 3 
} 

我迄今爲止嘗試:

collection.aggregate(
     [ 
      { 
       $group:{ // group by building 
        _id: {BUILDING}, 
        DEVCLASS: {DEVCLASS} // save devclass as property 
       } 
      } 
     ] 
    ) 

這似乎是$count運營商是不是在我的案件有幫助?

$ count 返回一個文檔,其中包含輸入舞臺的文檔數量的計數。

我已閱讀文檔,但現在我卡住了。我怎樣才能達到這個結果?

+0

嘗試'collection.aggregate( [ {$ 組:{ _id:{建設: 「$大樓」,DEVICECLASS :「$ DEVICECLASS」} COUNT:{$ sum:1} } } ] )' – Veeram

+0

@V eeram使用此我只得到所有設備的總數量不知道在一個給定的設備類的設備的計數的位置 –

回答

1

嘗試:

collection.aggregate([{$group:{_id:{"building" : "$building", "deviceclass":"$deviceclass"},count:{$sum:1} }}, 
     {$group:{_id:{"building" : "$_id.building" },result : {$push : {"deviceclass" : "$_id.deviceclass","count" : "$count"}}}}, 
     {$project : {"building" : "$_id.building" , "deviceclass" : "$result",_id:0}} 
    ]) 

您將獲得:

{ 
    "building" : "building xy", 
    "deviceclass" : [ 
     { 
      "deviceclass" : "mobile phone", 
      "count" : 2.0 
     }, 
     { 
      "deviceclass" : "destkop", 
      "count" : 1.0 
     } 
    ] 
} 
+0

泰,這是工作。它是如何工作就好了,這樣我就可以按照步驟聚集...建設和設備類的 –

+0

第一組,以便數據在建設和設備類的分組wise..after該組的建設,使相同的設備類具有相同的建築是一些評論顯示在結果中 –