2017-01-29 34 views
0

我的文件是這樣的:MongoDB的組相同的id子對象,並得到平均值

{ 
     "_id" : ObjectId("588e505fcdefc41e84c184cb"), 
     "Id" : 58614891, 
     "modifyDate" : 1485567717000, 
     "data" : [ 
       { 
         "id" : 99, 
         "stats" : { 
           "totalDepth" : 4, 
           "totalSpeed" : 2, 
           "totalLostSessions" : 2, 
           "KDI" : 8, 
         } 
       }, 
       { 
         "id" : 18, 
         "stats" : { 
           "totalDepth" : 2, 
           "totalSpeed" : 1, 
           "totalLostSessions" : 1, 
           "KDI" : 2, 
         } 
       } 
     ], 
     "timestampPull" : 1485721695291, 
     "region" : "eu", 
     "Status" : 200 
} 
{ 
     "_id" : ObjectId("588e5060cdefc41e84c184cd"), 
     "Id" : 38004043, 
     "modifyDate" : 1485515118000, 
     "data" : [ 
       { 

       { 
         "id" : 18, 
         "stats" : { 
           "totalDepth" : 5, 
           "totalSpeed" : 3, 
           "totalLostSessions" : 2, 
           "KDI" : 14, 
         } 
       }, 
       { 
         "id" : 62, 
         "stats" : { 
           "totalDepth" : 1, 
           "totalSpeed" : 0, 
           "totalLostSessions" : 1, 
           "KDI" : 1, 
         } 
       }, 
       { 
         "id" : 0, 
         "stats" : { 
           "totalDepth" : 155, 
           "totalSpeed" : 70, 
           "totalLostSessions" : 85, 
           "KDI" : 865, 
         } 
       } 
     ], 
     "timestampPull" : 1485721696025, 
     "region" : "na", 
     "Status" : 200 
} 

,我想,如果「數據」 ID匹配來計算每一個統計的平均值。

{ 
         "id" : 99, 
         "stats" : { 
           "totalDepth" : 4, 
           "totalSpeed" : 2, 
           "totalLostSessions" : 2, 
           "KDI" : 8, 
         } 
}, 
{ 
        "id" : 18, 
        "stats" : { 
          "totalDepth" : 3.5, 
          "totalSpeed" : 2, 
          "totalLostSessions" : 1.5, 
          "KDI" : 8, 
        } 
} ... 

可以在mongoDB上執行這樣的操作嗎?我可以輕鬆地將每個數據提取到應用程序並將其平均化,但這不是非常有效。

回答

1

您可以嘗試下面的聚合。

$unwinddata array。

$group通過id和計算值的$avgcount$sum值的數量。

$match保持數據,其中countgt大於1

db.collection.aggregate({ 
    $unwind: "$data" 
}, { 
    $group: { 
     _id: "$data.id", 
     count: { 
      $sum: 1 
     }, 
     "totalDepth": { 
      $avg: "$data.stats.totalDepth" 
     }, 
     "totalSpeed": { 
      $avg: "$data.stats.totalSpeed" 
     }, 
     "totalLostSessions": { 
      $avg: "$data.stats.totalLostSessions" 
     }, 
     "KDI": { 
      $avg: "$data.stats.KDI" 
     } 
    } 
}, { 
    $match: { 
     count: { 
      $gt: 1 
     } 
    } 
}) 
+0

謝謝你,工程完全按照我想要的。 – Nefritox