我有Collection" cars"从那里想要获得认证汽车的数量为trueCount和flaseCount,其中认证是布尔值。
发出以下mapreduce查询
图谱: -
function(key, values) {
certifiedCount = { trueCount: 0, falseCount: 0 };
values.forEach(function(value) {
if ( value.certifiedCheck )
certifiedCount.trueCount += value.count;
else
certifiedCount.falseCount += value.count;
});
return certifiedCount;
减少: -
{ "type": "cars" }
查询:
{ "id" : "carName" , "value" : { "true" : 277.0 , "false" : NaN}};
获得以下结果:
set()
即使我在集合中有457个文档。
请有人帮我解决这个问题。
提前致谢
答案 0 :(得分:0)
你混淆了map-reduce:减少到两个键“true”和“false”你需要将它们作为键发出。然后,reducer将按键运行。
伪代码:
{
"customer_id" : 1001,
"order_amount" : 15.00,
"timestamp" : 1465450000, //epoch time when order was placed
}
这应该产生两个文档,其中true / false为键,相应的和为值。
答案 1 :(得分:0)
您应该考虑使用 aggregation framework 来运行聚合,因为它实现了相同的结果,尽管比MapReduce更快,因为聚合在服务器(C ++)中本地运行,MapReduce会生成单独的javascript线程(s)运行JS代码。
如上所述,如果您运行以下聚合管道,该管道使用 $cond
运算符根据字段表达式中的逻辑计算计数,您将得到类似的结果:< / p>
因为你还没有展示你的集合架构,所以我假设你的mapReduce中有cars
字段作为数组的以下示例文档,你在{{1属性:
填充测试集合
cars
运行聚合操作
db.collection.insert([
{ _id: 1, cars: [ { model: "A", certified: true }, { model: "B", certified: true } ] },
{ _id: 2, cars: [ { model: "A", certified: false }, { model: "B", certified: true } ] },
{ _id: 3, cars: [ { model: "A", certified: true }, { model: "B", certified: false } ] },
{ _id: 4, cars: [ { model: "A", certified: true }, { model: "B", certified: false } ] },
{ _id: 5, cars: [ { model: "A", certified: true }, { model: "B", certified: true } ] }
])
<强>结果:强>
db.collection.aggregate([
{ "$unwind": "$cars" },
{
"$group": {
"_id": "$cars.model",
"trueCount": {
"$sum": {
"$cond": [ "$cars.certified", 1, 0 ]
}
},
"falseCount": {
"$sum": {
"$cond": [ "$cars.certified", 0, 1 ]
}
}
}
}
])