【发布时间】:2017-06-11 14:45:55
【问题描述】:
我有一个带有属性的产品的 mongo 集合:
{
"_id" : ObjectId("5888a2860c001d31a1089958"),
"product_id" : "107",
"store_id" : 0,
"attributes" : [{
"key" : "m",
"value" : 21,
"label" : "Mothercare"
}, {
"key" : "sp",
"value" : 10.0,
"label" : 10.0
}, {
"key" : "pr",
"value" : 2,
"label" : "150-300"
}, {
"key" : "c",
"value" : 59,
"label" : "Category 1"
}, {
"key" : "c",
"value" : 86,
"label" : "Category 2"
}, {
"key" : "c",
"value" : 134,
"label" : "Category 3"
}, {
"key" : "c",
"value" : 1013,
"label" : "Category 4"
}, {
"key" : "c",
"value" : 1063,
"label" : "Category 5"
}, {
"key" : "c",
"value" : 1073,
"label" : "Category 6"
}, {
"key" : "13",
"value" : 270,
"label" : "Brown"
}, {
"key" : "18",
"value" : 125,
"label" : "Girl"
}, {
"key" : "19",
"value" : 298,
"label" : "0-3 month"
}, {
"key" : "19",
"value" : 299,
"label" : "3-6 month"
}, {
"key" : "19",
"value" : 300,
"label" : "6-9 month"
}, {
"key" : "19",
"value" : 301,
"label" : "9-12 month"
}]
}
我需要找到快速获取集合中所有属性的计数的方法。我曾尝试使用 MapReduce:
function map() {
var max = this.attributes.length;
var key = {};
for (var i = 0; i < max; i++) {
key = {
key: this.attributes[i]['key'],
value: this.attributes[i]['value'],
}
emit(key, {count: 1});
}
}
function reduce(key, values) {
var sum = 0;
values.forEach(function(value) {
sum += value['count'];
});
return {count: sum};
};
但是很慢:
timeMillis=2420
counts={ "input" : 18963, "emit" : 221232, "reduce" : 7341, "output" : 1289 }
如何更快地找到所有属性的数量?我需要它用于产品过滤器。也许我必须使用其他集合结构?
我不需要找到属性的总数,我需要找到每个属性的计数,例如:
{ "key" : "c", "value" : 59 } 有 2345 个产品
{ "key" : "m", "value" : 21 } 有 258 个产品
【问题讨论】:
标签: mongodb mapreduce mongodb-query aggregation-framework