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