1

這裏是我的MongoDB集合模式:MongoDB在不同文檔中的數組中的項目聚合計數?

company: String 
model: String 
tags: [String] 

我需要聚合,所以我得到以下輸出:

[{ 
    "_id": { 
    "company": "Lenovo", 
    "model": "T400" 
    }, 
    "tags": { 
    tag: "SomeTag" 
    count: 124 // number of times, this tag was found in `Lenovo T400` 
    } 
}...] 

我試着做到以下幾點:

var aggParams = {}; 
aggParams.push({ $unwind: '$tags' }); 
aggParams.push({ $group: { 
    _id: { company: '$company', model: '$model' }, 
    tags: { $push: { tag: '$tags', count: { $sum: 1 } } }, 
}}); 

但我得到以下錯誤:

invalid operator '$sum' 

aggregation這樣做的正確方法是什麼?

+0

您的數據與您的模式相矛盾。什麼是實際數據中的「標籤」?一個字符串?還是數組? –

+0

'[String]' - 表示** **字符串數組** –

回答

3

您需要在數組上處理$unwind以便在聚合中處理它。你也可以添加到一個數組中並「計數」一個單獨的階段。除了聚集在管道的論據本身「陣列」,而不是你已經定義了一個對象:

Model.aggregate([ 
    { "$unwind": "$tags" }, 
    { "$group": { 
     "_id": { 
      "company": "$company", 
      "model": "$model", 
      "tag": "$tags" 
     }, 
     "count": { "$sum": 1 } 
    }}, 
    { "$group": { 
     "_id": { 
      "company": "$_id.company", 
      "model": "$_id.model", 
     }, 
     "tags": { "$push": { "tag": "$_id.tag", "count": "$count" } 
    }} 
], function(err,result) { 

}) 

於是兩個$group階段就終止了。一種是總結公司和模型中的標籤,另一種是將「公司」和「模型」分組,然後將不同的標籤和計數添加到數組中。

相關問題