I need help with writing function with map-reduce. I have such collection and aggregation function with it:
import pymongo
db_client = pymongo.MongoClient("mongodb://localhost:27017/")
current_db = db_client["pyloungedb"]
collection2 = current_db["Abonement bought"]
abonement_bought = [
{'ID': 1000,'client_id': 2 , 'price': 10,'client': 'Petras Petraitis','start_date': '2022.10.14','end_date': '2022.10.14'},
{'ID': 1000, 'client_id': 1, 'price': 30,'client': 'Jonas Jonaitis','start_date': '2021.09.14','end_date': '2022.10.14'},
{'ID': 1002, 'client_id': 3, 'price': 300,'client': 'Monika Mokaite','start_date': '2020.10.14','end_date': '2021.10.14'}
]
ins_result = collection2.insert_many(abonement_bought)
print(ins_result.inserted_ids)
agg_result= collection2.aggregate(
[{
"$group" :{
"_id" : "$ID",
"Total" : {"$sum" : 1},
"revenue":{"$sum" : "$price"}}}
])
for i in agg_result:
print(i)
I have to rewrite this with map-reduce function. Note: var doesn’t work, so I have a code, which should work, just I get empty result after printing it
def mapReduce():
mapf = "function(){emit(this.$ID, this.$price)}"
reducef = "function(k, v) { return Array.sum(v) }"
result = current_db.command(
'mapReduce',
'collection2',
map=mapf,
reduce=reducef,
out={'inline': 1})
print(result)
mapReduce()
Output: {‘results’: , ‘ok’: 1.0}
Using JupyterLab Python