I’m trying to calculate all documents where a certain field exists (in this case it’s “country” field) with Map+Reduce, and the only solution that worked for me is this:
mapper = Code("""
function () {
if (typeof this.country != 'undefined') {
var key = 1
emit(key, {count: 1})
};
};
""")
I’m not really interested in keys, just if field exists, so I just passed 1.
But I’m sure that’s wrong.
reducer = Code("""
function (key, values) {
var sum = 0;
values.forEach(function (value) {
sum += value['count'];
});
return {count: sum};
};
""")
And then calling 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'))
Also I’m thinking on how to get the amount of docs where their creation date is > than other date, should I use a “query” option in map_reduce function?
query = {"foundationDate":{"$gt":datetime.datetime(2012, 1, 1, 00, 00, 00)}}
Thank you 🙂
Per Chien-Wei Huang comment, why not use the in built functionality e.g.
Else if you want some token map-reduce code you cold simply mimic the count functionality, via the group() function e.g.
Note: If you also want a count by country value, then stick the following in the key:
, key { “country” : 1 }