2015-09-08 140 views
0

我在MongoDB中MongoDB的聚合 - 總和,其中

類似下面一個大的數據集我想運行在MongoDB中的聚集這將是該SQL相當於:

SELECT SUM(cores) from machines 
WHERE idc='AMS' AND cluster='1' AND type='Physical'; 

我該如何去關於在MongoDB中進行此操作?

[ 
    { 
     "_id" : "55d5dc40281077b6d8af1bfa", 
     "hostname" : "x", 
     "domain" : "domain", 
     "description" : "VMWare ESXi 5", 
     "cluster" : "1", 
     "type" : "Physical", 
     "os" : "EXSi", 
     "idc" : "AMS", 
     "environment" : "DR", 
     "deviceclass" : "host", 
     "cores" : "64", 
     "memory" : "256", 
     "mounts" : [ ], 
     "roles" : [ 
       "ESX-HOST" 
     ], 
     "ipset" : { 
       "backnet" : "1" 
     }, 
     "frontnet" : [ ], 
     "created" : "2015-09-08T07:35:03.343Z" 
    }, 
    { 
     "_id" : "55d5dc40281077b6d8af1bfb", 
     "hostname" : "x", 
     "domain" : "domain", 
     "description" : "VMWare ESXi 5", 
     "cluster" : "1", 
     "type" : "Physical", 
     "os" : "EXSi", 
     "idc" : "AMS", 
     "environment" : "DR", 
     "deviceclass" : "host", 
     "cores" : "64", 
     "memory" : "256", 
     "mounts" : [ ], 
     "roles" : [ 
       "ESX-HOST" 
     ], 
     "ipset" : { 
       "backnet" : "1" 
     }, 
     "frontnet" : [ ], 
     "created" : "2015-09-08T07:35:03.346Z" 
    } 
] 
+1

有手冊中的網頁的所有作爲示例的通用操作:[SQL到聚合映射圖](http://docs.mongodb.org/v3 0.0 /參考/ SQL-聚集比較/)。我建議你閱讀它 –

+2

你真的不需要爲此聚合。我認爲使用想要的是['.count'](http://docs.mongodb.org/manual/reference/method/db.collection.count/),因爲它(SUM)(_id)在這裏沒有意義。 – styvane

+0

對不起 - 錯字 - 現在它應該更有意義 – Corbin

回答

4

首先您需要更新您的文檔,因爲cores值是字符串而不是數字。爲此,我們使用"Bulk"操作。

var bulk = db.machines.initializeOrderedBulkOp(), 
    count = 0; 
db.machines.find({ "cores": { "$type": 2 }}).forEach(function(doc){ 
    var cores = parseInt(doc.cores); 
    bulk.find({ "_id": doc._id }).update({  
     "$set": { "cores": cores } }) 
     count++; 
     if (count % 200 == 0){ 
      // execute per 200 operations and re-init 
      bulk.execute();  
      bulk = db.machines.initializeOrderedBulkOp(); 
     } 
    }) 

// clean up queues 
if (count % 200 != 0) 
    bulk.execute(); 

然後,使用聚合框架,然後我們可以得到cores總和。首先,我們需要使用$match運算符和$group階段過濾我們的文檔,我們使用$sum運算符獲得cores值的總和。

db.machines.aggregate([ 
    { "$match": { "idc": "AMS", "cluster": "1", "type": "Physical" }}, 
    { "$group": { "_id": null, "sum_cores": { "$sum": "$cores" }}} 
]) 

它返回:

{ "_id" : null, "sum_cores" : 128 } 
0

雖然我沒有執行它來測試它檢查:

db.<collection>.aggregation([ 
{$match: { 
     idc: 'AMS', 
     cluster: 1, 
     type:'Physical' 
    } 
}, 
{$group: { 
      _id: null, 
      sum: {$sum: "$_id"} 
    } 
}, 
{$project: { 
     _id:0, 
     sum:1 
    } 
} 

])

0

我認爲使用聚合框架是不可能的,因爲'cores'保存爲string,目前mongo不允許在$project流水線階段作爲數字投射字符串。使用簡單的JavaScript 相同的結果:

var tmp = db.cores.find({idc: 'AMS', cluster: '1', type: 'Physical'}, {_id: 0, cores: 1}) 
var totalCores = 0; 
tmp.forEach(function(doc) { 
    totalCores += parseInt(doc.cores); 
}) 

print(totalCores) 

,如果我理解正確的問題。