2015-07-21 42 views
0

我有一個的MongoDB與以下形式的文件:格式化從MongoDB的/貓鼬組返回的對象由

{ 
    ... 
    "template" : "templates/Template1.html", 
    ... 
} 

其中template要麼"templates/Template1.html""templates/Template2.html""templates/Template3.html"

我使用這個查詢組由template並指望有多少次,每次template用於:

var group = { 
     key:{'template':1}, 
     reduce: function(curr, result){ result.count++ }, 
     initial: { count: 0 } 
    }; 

    messageModel.collection.group(group.key, null, group.initial, group.reduce, null, true, cb); 

我找回正確的結果,但它的格式如下:

{ 
    "0" : { 
     "template" : "templates/Template1.html", 
     "count" : 2 }, 
    "1" : { 
     "template" : "templates/Template2.html", 
     "count" : 2 }, 
    "2" : { 
     "template" : "templates/Template3.html", 
     "count" : 1 } 
} 

我想知道是否有可能更改查詢,以便它返回這樣的:

{ 
    "templates/Template1.html" : { "count" : 2 }, 
    "templates/Template2.html" : { "count" : 2 }, 
    "templates/Template3.html" : { "count" : 1 } 
} 

甚至:

{ 
    "templates/Template1.html" : 2 , 
    "templates/Template2.html" : 2 , 
    "templates/Template3.html" : 1 
} 

我寧願更改查詢,而不是從原始查詢解析返回的對象。

+0

要清楚的是,從'.group()'和其他許多運算符返回的值實際上是對象的「數組」,而不是表示它的單個對象。使用「數據」作爲「密鑰」也是一種「反模式」,在可重複使用的代碼中尤其是數據處理中應避免這種「反模式」。比較可靠的'.group()'選項更好的選擇是諸如聚合框架之類的東西。但是同樣的方式,輸出最好是一個「光標」而不是一個單獨的對象。所以讓數據庫成爲數據庫並且破壞你自己的結果。 –

回答

0

正如Blakes Seven在評論中提到的,您可以使用aggregate()而不是group()來達到您所期望的效果。

messageModel.collection.aggregate([ 
    { // Group the collection by `template` and count the occurrences 
    $group: { 
     _id: "$template", 
     count: { $sum: 1 } 
    } 
    }, 
    { // Format the output 
    $project: { 
     _id: 0, 
     template: "$_id", 
     count: 1 
    } 
    }, 
    { // Sort the formatted output 
    $sort: { template: 1 } 
    } 
]); 

輸出看起來像這樣:

[ 
    { 
    "template" : "templates/Template1.html", 
    "count" : 2 }, 
    { 
    "template" : "templates/Template2.html", 
    "count" : 2 }, 
    { 
    "template" : "templates/Template3.html", 
    "count" : 1 } 
    } 
] 

同樣,如在評論由布雷克規定的數據庫只能輸出對象,而不是一個孤立的對象的陣列。這將是您需要在數據庫之外完成的轉換。

我認爲值得重申的是,這種轉變產生了反模式,應該避免。對象鍵名稱提供了該值的上下文或描述。使用文件位置作爲關鍵名稱將是一個相當模糊的描述,而「模板」則提供了關於該值所代表的更多信息。