0

我讨厌重新发布这些东西,但我觉得我输入的语法与我查找的大多数问题完全相同。我试图简单地计算价格大于 9000 的行数。有人可以告诉我我做错了什么吗?

var map1 = function(){
    if(this.price > 9000) {
        emit(this._id, {count: 1});
    }
};

var red1 = function(keyId, values){
    var count = 0;
    values.forEach(function(v) {
            count +=v['count'];
            });

    return{count: count};
}

db.plots.mapReduce(map1, red1, {out: "query1"})

我的结果是这样的......

> db.query1.find()
{ "_id" : ObjectId("5170609afa9e8646fc906815"), "value" : { "count" : 1 } }
{ "_id" : ObjectId("5170609afa9e8646fc906816"), "value" : { "count" : 1 } }
{ "_id" : ObjectId("5170609afa9e8646fc90681c"), "value" : { "count" : 1 } }
{ "_id" : ObjectId("5170609afa9e8646fc906834"), "value" : { "count" : 1 } }
{ "_id" : ObjectId("5170609afa9e8646fc90683e"), "value" : { "count" : 1 } }
{ "_id" : ObjectId("5170609afa9e8646fc906846"), "value" : { "count" : 1 } }
{ "_id" : ObjectId("5170609afa9e8646fc90684b"), "value" : { "count" : 1 } }
{ "_id" : ObjectId("5170609afa9e8646fc90684e"), "value" : { "count" : 1 } }
{ "_id" : ObjectId("5170609afa9e8646fc906851"), "value" : { "count" : 1 } }
{ "_id" : ObjectId("5170609afa9e8646fc90685a"), "value" : { "count" : 1 } }
{ "_id" : ObjectId("5170609afa9e8646fc906861"), "value" : { "count" : 1 } }
{ "_id" : ObjectId("5170609afa9e8646fc906864"), "value" : { "count" : 1 } }
{ "_id" : ObjectId("5170609afa9e8646fc906879"), "value" : { "count" : 1 } }
{ "_id" : ObjectId("5170609afa9e8646fc906882"), "value" : { "count" : 1 } }
{ "_id" : ObjectId("5170609afa9e8646fc906883"), "value" : { "count" : 1 } }
{ "_id" : ObjectId("5170609afa9e8646fc90688b"), "value" : { "count" : 1 } }
{ "_id" : ObjectId("5170609afa9e8646fc90688c"), "value" : { "count" : 1 } }
{ "_id" : ObjectId("5170609afa9e8646fc906891"), "value" : { "count" : 1 } }
{ "_id" : ObjectId("5170609afa9e8646fc906894"), "value" : { "count" : 1 } }
{ "_id" : ObjectId("5170609afa9e8646fc90689a"), "value" : { "count" : 1 } }

我想要的是只取回一个号码。

4

1 回答 1

3

您做错了几件事-您为每个文档发出一个唯一键:由于 reduce 将所有文档与相同的键组合在一起,您没有得到聚合,因此您还将每个值与 9000 进行比较,而不是使用查询选项来映射/减少。

我不确定您为什么使用 map/reduce - 这对于聚合框架非常简单:

db.plots.aggregate([ {$match:{price:{$gt:9000}}}, 
                     {$group:{_id:null,count:{$sum:1}}}
] );

如果您有某些理由使用 map reduce 执行此操作,我建议您执行以下操作:

map = function() { emit(1, 1); }
reduce = function( key, values ) {
    var count = 0;
    values.forEach(function(v) {
            count +=v;
    });

    return count;
}

db.plots.mapReduce(map, reduce, {out: "query1", query:{price:{$gt:9000}}});
于 2013-04-20T03:20:30.890 回答