我有一个包含以下文档的项目集合。
{ "item" : "i1", "category" : "c1", "brand" : "b1" }
{ "item" : "i2", "category" : "c2", "brand" : "b1" }
{ "item" : "i3", "category" : "c1", "brand" : "b2" }
{ "item" : "i4", "category" : "c2", "brand" : "b1" }
{ "item" : "i5", "category" : "c1", "brand" : "b2" }
我想分离聚合结果-->按类别计数,按品牌计数。请注意,不按(类别、品牌)统计
我可以使用以下代码使用 map-reduce 来完成此操作。
map = function(){
emit({type:"category",category:this.category},1);
emit({type:"brand",brand:this.brand},1);
}
reduce = function(key, values){
return Array.sum(values)
}
db.item.mapReduce(map,reduce,{out:{inline:1}})
结果是
{
"results" : [
{
"_id" : {
"type" : "brand",
"brand" : "b1"
},
"value" : 3
},
{
"_id" : {
"type" : "brand",
"brand" : "b2"
},
"value" : 2
},
{
"_id" : {
"type" : "category",
"category" : "c1"
},
"value" : 3
},
{
"_id" : {
"type" : "category",
"category" : "c2"
},
"value" : 2
}
],
"timeMillis" : 21,
"counts" : {
"input" : 5,
"emit" : 10,
"reduce" : 4,
"output" : 4
},
"ok" : 1,
}
我可以通过触发两个不同的聚合命令来获得相同的结果,如下所示。
db.item.aggregate({$group:{_id:"$category",count:{$sum:1}}})
db.item.aggregate({$group:{_id:"$brand",count:{$sum:1}}})
无论如何,我可以通过单个聚合命令使用聚合框架执行相同的操作。
我在这里简化了我的情况,但实际上我需要对子文档数组中的字段进行分组。假设以上是我放松后的结构。
这是一个实时查询(有人等待响应),尽管数据集较小,因此执行时间很重要。
我正在使用 MongoDB 2.4。