1

我正在尝试使用 Map+Reduce 计算存在某个字段(在本例中为“国家”字段)的所有文档,唯一对我有用的解决方案是:

mapper = Code("""
function () {
if (typeof this.country != 'undefined') { 
    var key = 1
    emit(key, {count: 1})
    };
};
""")

我对键并不感兴趣,只要字段存在,所以我刚刚通过了 1。但我确定那是错误的。

reducer = Code("""
function (key, values) {
    var sum = 0;
    values.forEach(function (value) {
        sum += value['count'];
    });
    return {count: sum};
};
""")

然后调用 map_reduce:

results = dbHandle.cards.map_reduce(mapReduce.mapper, mapReduce.reducer, "resultsMR")
for doc in results.find():
    print "Found %s documents." % int(doc.get('value').get('count'))

另外我正在考虑如何获取创建日期大于其他日期的文档数量,我应该在 map_reduce 函数中使用“查询”选项吗?

query = {"foundationDate":{"$gt":datetime.datetime(2012, 1, 1, 00, 00, 00)}}

谢谢 :)

4

1 回答 1

0

Per Chien-Wei Huang评论,为什么不使用内置功能,例如

db.somName.find({"country":{"$exists":True}}).count() 

否则,如果您想要一些令牌映射减少代码,您只需通过group()函数模拟计数功能,例如

db.somName.group(
     { cond: { "country" : {$exists : true} }
      , key: { }
      , initial: {count : 0}
      , reduce: function(doc, out){ out.count++}
     }
  );

Note: If you also want a count by country value, then stick the following in the key: , key { "country" : 1 }

于 2012-11-15T15:05:46.637 回答