2014-12-05 68 views
1

這裏是我的問題:在我的蒙戈的數據庫,我有喜歡的項目集合:

{ 
    'id': 1, 
    'steps': [ 
    { 
     action: 'start', 
     info: 'foo' 
    }, 
    { 
     action: 'stop', 
     info: 'bar' 
    } 
    ] 
} 

我想獲得的步驟「開始」的總數。 我嘗試使用MongoDB彙總框架:我使用steps.action上的$unwindsteps.action上的$match來匹配'start'。

但是,我得到太多的數據並達到聚合的限制: exception: aggregation result exceeds maximum document size (16MB)。我不需要這些數據,我只是想要計數,但我無法找到如何去做(用$ group嘗試沒有成功)。

在此先感謝,

回答

8

如果你想計數您可以使用此

db.test.count({"steps.action":"start"}) 

但這不會考慮如果步驟包括多個步驟採取行動start

如果還需要用start來計算所有步驟,則需要展開數組,在steps.action上進行匹配,然後將結果分組計數。

db.test.aggregate({$unwind:"$steps"}, {$match:{"steps.action":"start"}},{ $group: { _id: null, count: { $sum: 1 } } }) 
+0

這隻給出開始計數,我們可以在單個查詢中同時獲得開始和結束計數。 – CodecPM 2016-04-07 10:49:17

-3

您可能不需要聚合此簡單查詢。見下面的代碼。

for (var i = 10000; i >= 0; i--) { 
    var a = { 
     'id': 1, 
     'steps': [ 
     { 
      action: 'start', 
      info: 'foo' 
     }, 
     { 
      action: 'stop', 
      info: 'bar' 
     } 
     ] 
    } 

    a.id = i; 
    var rnd = Math.floor((Math.random() * 3) + 1); 
    if (rnd == 1) 
    { 
     a.steps[0].action = 'none'; 
    } 
    if (rnd == 2) 
    { 
     a.steps.push({ action: 'start', info: 'foo' }) 

    } 
    db.obj.insert(a); 
}; 

此代碼創建隨機數的動作。 如果您只需要包含操作的文檔數量:「開始」,然後在下面查詢。

db.obj.count({"steps.action":"start"}) 

我在跑步中得到下面的計數。

> db.obj.count({"steps.action":"start"}) 
6756 

但是,如果您需要文檔中的{action:'start'}數量,那麼需要聚合查詢。 您放鬆身心,再搭配

db.obj.aggregate(
[ 
{ $unwind : "$steps"}, 
{$match: { "steps.action" : "start" }}, 
{ 
$group: 
{ 
    _id: null 
    ,count: { $sum: 1 } 
} 
} 
] 
) 

此輸出:

{ "_id" : null, "count" : 10054 } 



if you get your exception again use **allowDiskUse : true** option. See [here][1]. 

db.obj.aggregate(
[ 
.... 
] 
, 
{ 
    allowDiskUse : true 
} 

) 
+0

$ $匹配後放鬆不會產生正確的計數 – Jehof 2014-12-05 11:22:43

+0

爲什麼?如果我先過濾或過濾後有什麼關係? – 2014-12-05 11:44:48

+0

因爲$匹配不會減少steps-elements的元素,它只會查找具有action =「start」的數組元素的元素。 steps-array將包含與以前相同的元素。 – Jehof 2014-12-05 11:50:18

2

試試這個

db.collection.aggregate(
    { $unwind : "$steps" }, 
    {$match:{'steps.action':'start'}}, 
    {$group:{_id:null,count:{$sum:1}}} 
).pretty() 
0

在MongoDB中,聚合框架,流水線級具有最高100MB大小的限制,同時它提供的結果要麼是BSON文件或收集文件的最大大小爲16MB 所以你可以在$match只需要條件和$group它,這樣只有所需的結果輸出小於16MB。