2015-07-21 36 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 } 
    } 
] 

同样,如在评论由布雷克规定的数据库只能输出对象,而不是一个孤立的对象的阵列。这将是您需要在数据库之外完成的转换。

我认为值得重申的是,这种转变产生了反模式,应该避免。对象键名称提供了该值的上下文或描述。使用文件位置作为关键名称将是一个相当模糊的描述,而“模板”则提供了关于该值所代表的更多信息。