Tuesday, November 1, 2011

how to: python mongodb map-reduce

it's simple example how-to use map-reduce in mongo with python script
use:

  • python3
  • pymongo3 library





import pymongo
from datetime import datetime, timedelta
from  pymongo.code import Code
MAP_FUNCTION = Code("function () { emit(this.player, { count:1, score:this.score} ); }")
REDUCE_FUNCTION = Code("function (key, values) {var result = {count:0, score:0}; values.forEach(function (value) {result.count += value.count; result.score += value.score;}); return result; }")
dbhost=""
dbport=27017
mongodb = pymongo.Connection(dbhost, dbport)
db = mongodb.
age=10 
query={'last_visited': {'$gte': datetime.utcnow()-timedelta(age)}}
result = db..map_reduce(map=MAP_FUNCTION, reduce=REDUCE_FUNCTION, out="output", query=query)
for item in result.find():
    player = item["_id"]
    score = item["value"]['score']
    print(player, score)


No comments: