今天我擺弄了很多。關鍵字參數scope
需要是字典。如果你想定義一個變量作爲映射器範圍內的一個函數,將其名稱作爲鍵,並提供包裝在構造函數中的函數聲明。以下是MongoDB v3.2.8和pymongo v3.3.1的一個工作示例:
import pymongo
import bson
db = pymongo.MongoClient().test
db['test-input'].insert_many([
{'foo': 'bar', 'angle': 0},
{'foo': 'bar', 'angle': 90},
{'foo': 'baz', 'angle': -90}
])
mapper = bson.Code(
"""
function map() {
emit(this.foo, radians(this.angle))
}
"""
)
reducer = bson.Code(
"""
function reduce(key, values) {
var avg = 0;
for (i in values) {
avg += values[i];
}
return avg/values.length;
}
"""
)
output_collection = db['test-input'].map_reduce(
mapper, reducer, 'test-output',
scope={
'radians': bson.Code("function(x) {return x * Math.PI/180}")
}
)
print [x for x in output_collection.find()]